Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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.

Code

#!/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;
}

References