Skip to content
Myr

main.rs

This file

Path

examples/websockets/src/main.rs

247 lines · 8.5 KiB · Rust

Last changed by

chore: fix typos (#3758)David Pedersenbefore adoption5bc0046

History of this file

Take it

1//! Example websocket server.2//!3//! Run the server with4//! ```not_rust5//! cargo run -p example-websockets --bin example-websockets6//! ```7//!8//! Run a browser client with9//! ```not_rust10//! firefox http://localhost:300011//! ```12//!13//! Alternatively you can run the rust client (showing two14//! concurrent websocket connections being established) with15//! ```not_rust16//! cargo run -p example-websockets --bin example-client17//! ```1819use axum::{20    body::Bytes,21    extract::ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade},22    response::IntoResponse,23    routing::any,24    Router,25};26use axum_extra::TypedHeader;2728use std::ops::ControlFlow;29use std::{net::SocketAddr, path::PathBuf};30use tower_http::{31    services::ServeDir,32    trace::{DefaultMakeSpan, TraceLayer},33};3435use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};3637// Allows extracting the IP of the connecting user38use axum::extract::connect_info::ConnectInfo;39use axum::extract::ws::CloseFrame;4041// Allows splitting the websocket stream into separate TX and RX branches42use futures_util::{sink::SinkExt, stream::StreamExt};4344#[tokio::main]45async fn main() {46    tracing_subscriber::registry()47        .with(48            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {49                format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()50            }),51        )52        .with(tracing_subscriber::fmt::layer())53        .init();5455    let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");5657    // build our application with some routes58    let app = Router::new()59        .fallback_service(ServeDir::new(assets_dir).append_index_html_on_directories(true))60        .route("/ws", any(ws_handler))61        // logging so we can see what's going on62        .layer(63            TraceLayer::new_for_http()64                .make_span_with(DefaultMakeSpan::default().include_headers(true)),65        );6667    // run it with hyper68    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")69        .await70        .unwrap();71    tracing::debug!("listening on {}", listener.local_addr().unwrap());72    axum::serve(73        listener,74        app.into_make_service_with_connect_info::<SocketAddr>(),75    )76    .await;77}7879/// The handler for the HTTP request (this gets called when the HTTP request lands at the start80/// of websocket negotiation). After this completes, the actual switching from HTTP to81/// websocket protocol will occur.82/// This is the last point where we can extract TCP/IP metadata such as IP address of the client83/// as well as things from HTTP headers such as user-agent of the browser etc.84async fn ws_handler(85    ws: WebSocketUpgrade,86    user_agent: Option<TypedHeader<headers::UserAgent>>,87    ConnectInfo(addr): ConnectInfo<SocketAddr>,88) -> impl IntoResponse {89    let user_agent = if let Some(TypedHeader(user_agent)) = user_agent {90        user_agent.to_string()91    } else {92        String::from("Unknown browser")93    };94    println!("`{user_agent}` at {addr} connected.");95    // finalize the upgrade process by returning upgrade callback.96    // we can customize the callback by sending additional info such as address.97    ws.on_upgrade(move |socket| handle_socket(socket, addr))98}99100/// Actual websocket statemachine (one will be spawned per connection)101async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {102    // send a ping (unsupported by some browsers) just to kick things off and get a response103    if socket104        .send(Message::Ping(Bytes::from_static(&[1, 2, 3])))105        .await106        .is_ok()107    {108        println!("Pinged {who}...");109    } else {110        println!("Could not send ping {who}!");111        // no Error here since the only thing we can do is to close the connection.112        // If we can not send messages, there is no way to salvage the statemachine anyway.113        return;114    }115116    // receive single message from a client (we can either receive or send with socket).117    // this will likely be the Pong for our Ping or a hello message from client.118    // waiting for message from a client will block this task, but will not block other client's119    // connections.120    if let Some(msg) = socket.recv().await {121        if let Ok(msg) = msg {122            if process_message(msg, who).is_break() {123                return;124            }125        } else {126            println!("client {who} abruptly disconnected");127            return;128        }129    }130131    // Since each client gets individual statemachine, we can pause handling132    // when necessary to wait for some external event (in this case illustrated by sleeping).133    // Waiting for this client to finish getting its greetings does not prevent other clients from134    // connecting to server and receiving their greetings.135    for i in 1..5 {136        if socket137            .send(Message::Text(format!("Hi {i} times!").into()))138            .await139            .is_err()140        {141            println!("client {who} abruptly disconnected");142            return;143        }144        tokio::time::sleep(std::time::Duration::from_millis(100)).await;145    }146147    // By splitting socket we can send and receive at the same time. In this example we will send148    // unsolicited messages to client based on some sort of server's internal event (i.e .timer).149    let (mut sender, mut receiver) = socket.split();150151    // Spawn a task that will push several messages to the client (does not matter what client does)152    let mut send_task = tokio::spawn(async move {153        let n_msg = 20;154        for i in 0..n_msg {155            // In case of any websocket error, we exit.156            if sender157                .send(Message::Text(format!("Server message {i} ...").into()))158                .await159                .is_err()160            {161                return i;162            }163164            tokio::time::sleep(std::time::Duration::from_millis(300)).await;165        }166167        println!("Sending close to {who}...");168        if let Err(e) = sender169            .send(Message::Close(Some(CloseFrame {170                code: axum::extract::ws::close_code::NORMAL,171                reason: Utf8Bytes::from_static("Goodbye"),172            })))173            .await174        {175            println!("Could not send Close due to {e}, probably it is ok?");176        }177        n_msg178    });179180    // This second task will receive messages from client and print them on server console181    let mut recv_task = tokio::spawn(async move {182        let mut cnt = 0;183        while let Some(Ok(msg)) = receiver.next().await {184            cnt += 1;185            // print message and break if instructed to do so186            if process_message(msg, who).is_break() {187                break;188            }189        }190        cnt191    });192193    // If any one of the tasks exit, abort the other.194    tokio::select! {195        rv_a = (&mut send_task) => {196            match rv_a {197                Ok(a) => println!("{a} messages sent to {who}"),198                Err(a) => println!("Error sending messages {a:?}")199            }200            recv_task.abort();201        },202        rv_b = (&mut recv_task) => {203            match rv_b {204                Ok(b) => println!("Received {b} messages"),205                Err(b) => println!("Error receiving messages {b:?}")206            }207            send_task.abort();208        }209    }210211    // returning from the handler closes the websocket connection212    println!("Websocket context {who} destroyed");213}214215/// helper to print contents of messages to stdout. Has special treatment for Close.216fn process_message(msg: Message, who: SocketAddr) -> ControlFlow<(), ()> {217    match msg {218        Message::Text(t) => {219            println!(">>> {who} sent str: {t:?}");220        }221        Message::Binary(d) => {222            println!(">>> {who} sent {} bytes: {d:?}", d.len());223        }224        Message::Close(c) => {225            if let Some(cf) = c {226                println!(227                    ">>> {who} sent close with code {} and reason `{}`",228                    cf.code, cf.reason229                );230            } else {231                println!(">>> {who} somehow sent close message without CloseFrame");232            }233            return ControlFlow::Break(());234        }235236        Message::Pong(v) => {237            println!(">>> {who} sent pong with {v:?}");238        }239        // You should never need to manually handle Message::Ping, as axum's websocket library240        // will do so for you automagically by replying with Pong and copying the v according to241        // spec. But if you need the contents of the pings you can see them here.242        Message::Ping(v) => {243            println!(">>> {who} sent ping with {v:?}");244        }245    }246    ControlFlow::Continue(())247}