I am using tokio-tungstenite to access a server. Unfortunately, the read operation does not work and the program exits with error code 0 so a priori no error. A simplified code (the "..." are not what I used though) would be
use tokio_tungstenite::connect_async;
use futures_util::StreamExt;
use futures_util::SinkExt;
#[tokio::main]
async fn main() {
let url_name = "wss://...";
let (ws_stream, _) = connect_async(url_name).await.unwrap();
let (mut write, mut read) = ws_stream.split();
tokio::spawn(async move {
let ent = read.next().await;
println!("We have ent");
});
write.send(tokio_tungstenite::tungstenite::Message::Text("...".to_string())).await;
}
The behavior of buggy program I would expect is either the read hanging out or the ent being None or if not None containing the error inside of it that I could interpret. But no the program exits without error messages.
Besides the immediate issue of what is wrong, what could be a debugging approach for understanding what is happening in tokio?
CodePudding user response:
Your program exits after the write.send(...)
future yields a result. This result is discarded, so it doesn't influence the exit code of your program.
The compiler actually emits a warning for unused results, hinting that you should be handling that.
If you want to bubble up the error state of your write operation, you can unwrap()
the result returned by it. If writing to the underlying WebSocket fails, your program will panic and exit.
If the write operation succeeds and you want to wait for the read operation, you'll need to bind the JoinHandle
returned by tokio::spawn
to a variable and await it, i.e.
let handle = tokio::spawn(async move {
let ent = read.next().await.expect("Stream ended").expect("Error while reading");
println!("We have ent");
});
write.send(tokio_tungstenite::tungstenite::Message::Text("...".to_string())).await.expect("Failed to write the message");
handle.await.expect("The read task failed.");
The handle
's future will return an error if the underlying task panicked, which would be the case if the read operation failed.