How to use WebSockets in Rust

Web
Implement real-time bidirectional communication in Rust by using the WebSocketUpgrade extractor and on_upgrade handler.

Use the WebSocketUpgrade extractor to handle the handshake and on_upgrade to process the connection.

use axum::{
    extract::ws::{WebSocketUpgrade, WebSocket},
    routing::any,
    response::Response,
    Router,
};

let app = Router::new().route("/ws", any(handler));

async fn handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let msg = if let Ok(msg) = msg { msg } else { return; };
        if socket.send(msg).await.is_err() { return; }
    }
}