I am programming in Rust, creating a websocket client using tokio_tungstenite. However, I am getting a rather peculiar error. My code is below:
use std::env;
use futures::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio_tungstenite::connect_async;
#[tokio::main]
async fn main() {
env::set_var("RUST_BACKTRACE", "1");
let url = "wss://ws-feed.exchange.coinbase.com";
let msg = r#"
{
"type": "subscribe",
"product_ids": [
"ETH-USD"
],
"channels": [
"level2",
"heartbeat",
{
"name": "ticker",
"product_ids": [
"ETH-USD"
]
}
]
}"#;
match connect_async(url).await {
Ok((ws_stream, _)) => {
let (mut write, mut read) = ws_stream.split();
match write.send(Message::Text(msg.to_string())).await {
Ok(_) => println!("Message sent successfully"),
Err(e) => println!("Failed to send message: {}", e),
}
while let Some(msg) = read.next().await {
match msg {
Ok(msg) => println!("Received: {}", msg),
Err(e) => println!("Error reading message: {}", e),
}
}
},
Err(e) => println!("Failed to connect: {}", e),
}
}
Cargo.toml:
[dependencies]
futures = "0.3"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.15.0"
My error:
Failed to connect: HTTP error: 400 Bad Request
The reason it's peculiar is that the url works. I have a websocket client extension in Mozilla FireFox that I used the same url: wss://ws-feed.exchange.coinbase.com and message:
{
"type": "subscribe",
"product_ids": [
"ETH-USD"
],
"channels": [
"level2",
"heartbeat",
{
"name": "ticker",
"product_ids": [
"ETH-USD"
]
}
]
}
and it works. The extension is called Websocket Weasel.
The reason I have the backtrace in the code is because before I didn't include the match and I had a bad error that disappeared when I used the match, but now it compiles but without much information. Below was the error I had:
3: enum2$<core::result::Result<tuple$<tokio_tungstenite::WebSocketStream<enum2$<tokio_tungstenite::stream::MaybeTlsStream<tokio::net::tcp::stream::TcpStream> > >,http::response::Response<tuple$<> > >,enum2$<tungstenite::error::Error> > >::expect<tuple$<tokio
I am certain the error is in regards to the connection of the URL to the server. Any help would be greatly appreciated. You are awesome!