Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
RECIPE 03 / 8

A room that talks back.

A multi-client WebSocket chat room with a complete browser client.

BY NAVAN SAMI~25 MIN BUILDLOCAL PROJECT
Download this project ↓
Axum 0.8Tokio broadcastfutures-utilBrowser WebSocket

01 The shape of the build

WebSocket gives each client a persistent bidirectional connection. The server splits the socket into a reader and writer and uses a bounded Tokio broadcast channel to fan out accepted messages. A subscriber is created before the connection starts receiving messages. Each connected client, including the sender, receives room messages; there is no history, user identity, or durable delivery. Slow subscribers are disconnected when they lag behind the bounded channel, making the overload policy visible.

  1. 1

    Serve the client and /ws upgrade route from the same local origin.

  2. 2

    Split each socket so incoming and outgoing work can progress concurrently.

  3. 3

    Reject empty and over-512-byte text, then publish accepted text to the room.

  4. 4

    Disconnect lagging subscribers rather than silently pretending every message arrived.

  5. 5

    Open two browser tabs and confirm messages appear in both.

02 Get it running

Install Rust stable and extract this project’s ZIP. Run these commands from the extracted instant-chat folder. The full workbench keeps it under cookbook/instant-chat.

terminal
cargo run
# Open http://127.0.0.1:3002 in two tabs.
WHAT YOU SHOULD SEE

Each accepted message appears in all connected tabs. The UI reports connected, disconnected, and send errors. Refreshing shows an empty history.

First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.

03 The complete source

Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.

Cargo.toml11 lines +
Cargo.toml
[package]
name = "instant-chat"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "sync"] }
futures-util = "0.3"

[workspace]
src/main.rs66 lines +
src/main.rs
use axum::{
    Router,
    extract::{
        State,
        ws::{Message, WebSocket, WebSocketUpgrade},
    },
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Response},
    routing::get,
};
use futures_util::{SinkExt, StreamExt};
use tokio::sync::broadcast;
async fn upgrade(
    ws: WebSocketUpgrade,
    State(tx): State<broadcast::Sender<String>>,
    headers: HeaderMap,
) -> Response {
    if let Some(origin) = headers.get("origin") {
        if !matches!(
            origin.to_str(),
            Ok("http://127.0.0.1:3002" | "http://localhost:3002")
        ) {
            return StatusCode::FORBIDDEN.into_response();
        }
    }
    ws.max_message_size(1024)
        .max_frame_size(1024)
        .on_upgrade(move |socket| room(socket, tx))
}
async fn room(socket: WebSocket, tx: broadcast::Sender<String>) {
    let mut inbox = tx.subscribe();
    let (mut writer, mut reader) = socket.split();
    loop {
        tokio::select! {
            incoming=reader.next() => match incoming {
                Some(Ok(Message::Text(text))) => {
                    let text=text.trim();
                    if !text.is_empty() && text.len()<=512 { let _=tx.send(text.to_owned()); }
                },
                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
                _ => {}
            },
            outgoing=inbox.recv() => match outgoing {
                Ok(text) => { if writer.send(Message::Text(text.into())).await.is_err() { break; } },
                Err(_) => break,
            }
        }
    }
    let _ = writer.close().await;
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (tx, _) = broadcast::channel::<String>(64);
    let app = Router::new()
        .route(
            "/",
            get(|| async { Html(include_str!("../web/index.html")) }),
        )
        .route("/ws", get(upgrade))
        .with_state(tx);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3002").await?;
    println!("Open two tabs: http://127.0.0.1:3002");
    // Ctrl+C ends the process; active chat sockets are not durably drained.
    axum::serve(listener, app).await?;
    Ok(())
}
web/index.html14 lines +
web/index.html
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Build Lab / Chat</title>
<style>body{font:18px system-ui;background:#121212;color:#fff;max-width:680px;margin:8vh auto;padding:24px}h1{font-size:clamp(32px,8vw,64px)}em{color:#ff6034}form{display:flex;gap:10px}input{min-width:0;flex:1;padding:14px;font:inherit}button{background:#ff6034;color:#111;border:0;padding:14px;font:inherit}li{padding:10px;overflow-wrap:anywhere}p{color:#bbb}</style>
<h1>Small room.<br><em>Real conversation.</em></h1><p id="status" role="status">Connecting…</p>
<ul id="messages" aria-live="polite"></ul><form id="send"><input id="text" aria-label="Message" maxlength="512" required autocomplete="off"><button disabled>Send ↗</button></form>
<script>
const status=document.querySelector('#status'), list=document.querySelector('#messages'), input=document.querySelector('#text'), button=document.querySelector('button');
const socket=new WebSocket(`${location.protocol==='https:'?'wss':'ws'}://${location.host}/ws`);
socket.onopen=()=>{status.textContent='Connected / local demo room';button.disabled=false};
socket.onclose=()=>{status.textContent='Disconnected. Refresh to reconnect.';button.disabled=true};
socket.onerror=()=>{status.textContent='Connection error'};
socket.onmessage=event=>{const item=document.createElement('li');item.textContent=event.data;list.append(item);while(list.children.length>100)list.firstElementChild.remove();};
document.querySelector('form').onsubmit=event=>{event.preventDefault();const text=input.value.trim();if(new TextEncoder().encode(text).length>512){status.textContent='Use at most 512 UTF-8 bytes';return}if(text&&socket.readyState===WebSocket.OPEN){try{socket.send(text);input.value='';status.textContent='Connected / local demo room'}catch{status.textContent='Could not send'}}};
</script></html>

04 Check the behavior

  • □Two tabs receive the same submitted message, including the sender.
  • □Blank messages are not broadcast.
  • □HTML-looking text appears as literal text, never markup.
  • □Closing one tab does not stop the server or other clients.

05 Know what you are building on

One public local room, no authenticated identities, message history, or cross-process fan-out.

Messages can be lost on disconnect or slow-consumer eviction; this is not durable instant messaging.

A deployment needs authenticated room membership, origin policy for its real host, TLS, connection limits, and rate limits.

MAKE IT YOUR OWN

Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.