Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Connect A Listener To A Websocket Server In Rust With tokio - tungstenite

This is a cut down version of the client example from the tokio - tungstenite create. It connects to a websocket server and prints any messages it receives to the console.

rust
#!/usr/bin/env cargo +nightly -Zscript

//! ```cargo
//! [dependencies]
//! futures-util = { version = "0.3.28" }
//! tokio = { version = "1.0.0", features = ["full"] }
//! tokio-tungstenite = "*"
//! url = "2.4.1"
//! ```

use futures_util::StreamExt;
use tokio::io::AsyncWriteExt;
use tokio_tungstenite::connect_async;

#[tokio::main]
async fn main() {
    let address = "ws://127.0.0.1:3302/ws";
    let url = url::Url::parse(address).unwrap();
    let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
    println!("Connected");
    let (_, read) = ws_stream.split();
    let ws_to_stdout = {
        read.for_each(|message| async {
            let data = message.unwrap().into_data();
            tokio::io::stdout().write_all(&data).await.unwrap();
        })
    };
    ws_to_stdout.await;
}

- The original example read stdin and sent whatever it received to the server. There was a bunch of extra futures stuff invovled in that. I ripped all that out since I just want a listener client

- I'm still new to async/tokio/futures. This code is working in issolation. I don't know if it would need to be tweaked to work in more complicated coded bases

Footnotes And References