Skip to content

Instantly share code, notes, and snippets.

@tsidea
Last active September 14, 2022 04:22
Show Gist options
  • Save tsidea/405b7dcee638fd192f6b8461c51f5f9c to your computer and use it in GitHub Desktop.
Save tsidea/405b7dcee638fd192f6b8461c51f5f9c to your computer and use it in GitHub Desktop.
spawn task to handle websocket connection
use hyper::upgrade;
use tokio_tungstenite::WebSocketStream;
use futures::stream::StreamExt;
...
tokio::spawn(async move {
//using the hyper feature of upgrading a connection
match upgrade::on(&mut request).await {
//if successfully upgraded
Ok(upgraded) => {
//create a websocket stream from the upgraded object
let ws_stream = WebSocketStream::from_raw_socket(
//pass the upgraded object
//as the base layer stream of the Websocket
upgraded,
tokio_tungstenite::tungstenite::protocol::Role::Server,
None,
).await;
//FINALLY we have our websocket stream as ws_stream
//we can now split the stream into a sink and a stream
let (ws_write, ws_read) = ws_stream.split();
//forward the stream to the sink to achieve echo
match ws_read.forward(ws_write).await {
Ok(_) => {},
Err(Error::ConnectionClosed) =>
println!("Connection closed normally"),
Err(e) =>
println!("error creating echo stream on \
connection from address {}. \
Error is {}", remote_addr, e),
};
},
Err(e) =>
println!("error when trying to upgrade connection \
from address {} to websocket connection. \
Error is: {}", remote_addr, e),
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment