From rocket_ws documentation (https://api.rocket.rs/v0.5/rocket_ws/) I know I can establish websocket connection with the client with this pice of code:
#[get("/echo?channel")]
fn echo_channel(ws: ws::WebSocket) -> ws::Channel<'static> {
use rocket::futures::{SinkExt, StreamExt};
ws.channel(move |mut stream| Box::pin(async move {
while let Some(message) = stream.next().await {
let _ = stream.send(message?).await;
}
Ok(())
}))
}
But how can I detect that connection is closed and that the client was disconnected?
This example only shows use-case for reading messages with stream.next(), but what if I don't expect messages from client and just want to send him new values (with something like this let _ = stream.send(ws::Message::Text(json!(reading).to_string())).await;) periodically with let mut interval = interval(Duration::from_secs(10));?
To detect when client disconnects from the websocket you can listen for
Closemessage sent from the client.Code would look something like this:
So your whole code for handling websockets in Rust with rocket_ws would look something like this: