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.

Revisions

  1. tsidea revised this gist Feb 3, 2021. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion spawn_ws_conn.rs
    Original file line number Diff line number Diff line change
    @@ -18,7 +18,8 @@ tokio::spawn(async move {
    None,
    ).await;

    //we can split the stream into a sink and a stream
    //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
  2. tsidea created this gist Feb 1, 2021.
    40 changes: 40 additions & 0 deletions spawn_ws_conn.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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;

    //we can 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),
    }
    });