Use the tokio-tungstenite crate with the tokio runtime to create a non-blocking WebSocket server. This setup handles the async I/O required for real-time bidirectional communication.
use tokio_tungstenite::tungstenite::Message;
#[tokio::main]
async fn main() {
let server = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
println!("Listening on ws://127.0.0.1:8080");
loop {
let (socket, _) = tokio_tungstenite::accept_async(server.accept().await.unwrap()).await.unwrap();
tokio::spawn(async move {
let (mut write, mut read) = socket.split();
while let Ok(Some(msg)) = read.next().await {
if let Err(e) = write.send(msg).await {
eprintln!("Error sending: {e}");
break;
}
}
});
}
}
Add tokio = { version = "1", features = ["full"] } and tokio-tungstenite = "0.24" to your Cargo.toml.