Learn Axum ยท 11/13

Real-time Communication with WebSockets

7 min read

Course: Axum
Progress: 11/XX
Estimated Time: 20 mins ๐Ÿฆ€


๐Ÿ‘‹ Welcome to the "Live" Show

Hello, intrepid Rustacean! ๐Ÿฆ€

Up until now, our API has been very... transactional. Itโ€™s been a lot like mailing a letter: you send a request (letter), wait a bit, and get a response (reply). If you want to know if there's new mail, you have to go check the mailbox again. And again. And again.

In the industry, we call this Polling, and frankly, itโ€™s exhausting for your server. Imagine if your friend asked "Are we there yet?" every 2 seconds for a 4-hour drive. Youโ€™d want to abandon them at a gas station.

Today, we are ditching the letters and installing a direct telephone line. We are talking about WebSockets.

๐Ÿ’ก Did you know?

The WebSocket protocol (RFC 6455) was standardized in 2011. Before that, developers used "Long Polling" (Comet), which basically involved opening an HTTP request and... just never closing it until the server had data. It was like holding your breath and hoping for the best.


1. WebSocket Basics: The Connection Upgrade Process

Definition

A WebSocket is a computer communications protocol providing full-duplex (two-way) communication channels over a single TCP connection.

The Problem: HTTP Statelessness

HTTP is stateless. The server forgets who you are the moment it sends the response. To get real-time stock prices or chat messages, the client has to keep asking. This creates high latency and massive header overhead (sending cookies/auth tokens every single time).

The Solution: The Upgrade Handshake

WebSockets solve this by starting as a normal HTTP request and then "upgrading" to a persistent connection.

Think of it like this:

  1. Client: Knocks on the door (HTTP Request). "Hello! Can we speak in WebSocket?"
  2. Server: Checks credentials. "Sure! Let's switch protocols." (HTTP 101 Switching Protocols).
  3. Result: The door stays open. Both parties can shout data at each other whenever they want without knocking again.

Under the Hood

The client sends a header Connection: Upgrade and Upgrade: websocket. If the server agrees, the TCP connection remains open, but the rules of engagement change from HTTP to the WebSocket binary framing protocol.


2. The WebSocketUpgrade Extractor

In Axum, handling this "handshake" is surprisingly ergonomic. We don't parse headers manually; we use an Extractor.

๐Ÿ› ๏ธ Setup: Cargo.toml

First, you must enable the ws feature in Axum. If you miss this, nothing works, and you will be sad.

toml
[dependencies]
axum = { version = "0.7", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
futures = "0.3" # We need this for stream utilities

The Handler

The WebSocketUpgrade extractor tells Axum: "If this request is a WebSocket handshake, let me handle it. If not, reject it."

Here is the pattern:

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

async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    // 1. The handshake happens here automatically.
    // 2. We return a response that finalizes the upgrade.
    // 3. We pass a callback function (`handle_socket`) to handle the actual connection.
    ws.on_upgrade(handle_socket)
}

// This function handles the physical socket connection
async fn handle_socket(mut socket: WebSocket) {
    println!("Client connected! ๐Ÿ”Œ");
    
    // We'll add logic here in the next section
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/ws", get(ws_handler));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Listening on port 3000");
    axum::serve(listener, app).await.unwrap();
}

Key Takeaway: The ws_handler returns immediately. The actual long-running connection happens inside handle_socket, which runs on a separate Tokio task.


3. Sending and Receiving: Handling Message Streams

Once inside handle_socket, we are in the realm of Streams. The socket variable is both a Reader and a Writer.

The Loop

To keep the connection alive and process messages, we need a loop.

rust
use axum::extract::ws::Message;

async fn handle_socket(mut socket: WebSocket) {
    // "recv()" returns Option<Result<Message, Error>>
    while let Some(msg) = socket.recv().await {
        if let Ok(msg) = msg {
            match msg {
                Message::Text(text) => {
                    println!("Client said: {}", text);
                    
                    // Echo back
                    if let Err(e) = socket.send(Message::Text(format!("You said: {}", text))).await {
                        eprintln!("Error sending message: {}", e);
                        return;
                    }
                }
                Message::Binary(_) => println!("Client sent binary data"),
                Message::Ping(_) => println!("Client pinged ๐Ÿ“"), 
                Message::Pong(_) => println!("Client ponged"),
                Message::Close(_) => {
                    println!("Client disconnected");
                    return;
                }
            }
        } else {
            // Client disconnected abruptly
            return;
        }
    }
}

โš ๏ธ Industry Standard: Split the Stream

In real-world apps (like Chat), you might want to send a message without waiting for the client to speak first. Using socket for both reading and writing in a single loop is limiting.

We use split() to separate the Sender (Sink) from the Receiver (Stream).

rust
use futures::{sink::SinkExt, stream::StreamExt}; // Import traits!

async fn handle_socket(socket: WebSocket) {
    // Split the socket into a sender and receiver
    let (mut sender, mut receiver) = socket.split();

    // Spawn a task to listen for incoming messages
    let mut recv_task = tokio::spawn(async move {
        while let Some(Ok(msg)) = receiver.next().await {
            // Process message...
            println!("Received: {:?}", msg);
        }
    });

    // Spawn a task to send messages (simulated here)
    let mut send_task = tokio::spawn(async move {
        let _ = sender.send(Message::Text("Hello from server!".to_string())).await;
    });

    // Wait for either to finish (usually when client disconnects)
    tokio::select! {
        _ = (&mut recv_task) => send_task.abort(),
        _ = (&mut send_task) => recv_task.abort(),
    }
}

Note: Ping and Pong are heartbeat messages. Browsers handle Pings automatically. If you don't handle them, the connection might drop because routers think it's dead.


4. Broadcasting: Sharing Messages Across Clients

The Problem

If Client A sends "Hello", currently only Client A sees the echo. Client B sees nothing.
This is because every handle_socket runs in its own isolated Tokio task. They don't know each other exists.

The Solution: Tokio Broadcast Channels

To build a chat room, we need a "Bus" where one person yells, and everyone else hears it. We use tokio::sync::broadcast.

Architecture

  1. Create a broadcast::Sender in our App State.
  2. Pass this state to the handler.
  3. Inside the handler, subscribe to the channel.
rust
use axum::{
    extract::{ws::{Message, WebSocket, WebSocketUpgrade}, State},
    response::Response,
    routing::get,
    Router,
};
use std::sync::Arc;
use tokio::sync::broadcast;
use futures::{sink::SinkExt, stream::StreamExt};

// 1. Define App State
struct AppState {
    tx: broadcast::Sender<String>, // The transmission line
}

#[tokio::main]
async fn main() {
    // 2. Create the channel
    // Capacity of 100 messages. If a client lags behind by 100 msgs, they get an error.
    let (tx, _rx) = broadcast::channel(100); 

    let app_state = Arc::new(AppState { tx });

    let app = Router::new()
        .route("/ws", get(ws_handler))
        .with_state(app_state); // Inject state

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn ws_handler(
    ws: WebSocketUpgrade,
    State(state): State<Arc<AppState>>,
) -> Response {
    ws.on_upgrade(|socket| handle_socket(socket, state))
}

async fn handle_socket(socket: WebSocket, state: Arc<AppState>) {
    let (mut sender, mut receiver) = socket.split();

    // Subscribe to the broadcast channel
    let mut rx = state.tx.subscribe();
    
    // We need to clone the sender to use it inside the receiving loop
    let tx = state.tx.clone();

    // Task 1: Read from Client, Broadcast to everyone
    let mut recv_task = tokio::spawn(async move {
        while let Some(Ok(msg)) = receiver.next().await {
            if let Message::Text(text) = msg {
                // Broadcast the message!
                let _ = tx.send(text); 
            }
        }
    });

    // Task 2: Listen to Broadcast, Send to Client
    let mut send_task = tokio::spawn(async move {
        while let Ok(msg) = rx.recv().await {
            // Send the broadcasted message to THIS specific client
            if sender.send(Message::Text(msg)).await.is_err() {
                break;
            }
        }
    });

    // Wait until one task finishes (usually connection closed)
    tokio::select! {
        _ = (&mut recv_task) => send_task.abort(),
        _ = (&mut send_task) => recv_task.abort(),
    }
}

๐Ÿคฏ Real Life Scenario: The "Lagging" Receiver

In broadcast::channel(100), 100 is the buffer size.
Imagine a lecture hall. The professor (Sender) is speaking. The students (Receivers) are taking notes.
If one student falls asleep and wakes up 20 minutes later, they missed too much context. The professor cannot pause the whole class for that one student.
In code, this throws a RecvError::Lagged. You should handle this by telling the client "You missed messages, please refresh."


๐Ÿงช Hands-On Challenge

  1. Run the broadcast code.
  2. Open two different browser tabs.
  3. Use a WebSocket tester (or simple JS in console):
    javascript
    let ws = new WebSocket("ws://localhost:3000/ws");
    ws.onmessage = (event) => console.log("New Message:", event.data);
    ws.send("Hello from Tab 1!");
  4. Watch "Hello from Tab 1" appear in Tab 2's console! ๐Ÿš€

๐Ÿ“š References & Resources


Next Up: We've conquered the real-time wave. Next, we will look at Error Handling, because sometimes even the best code trips over its own shoelaces. See you there! ๐Ÿƒโ€โ™‚๏ธ

Challenge

Your task is to implement a function named reverseString that accepts a single string parameter, str.

This function should process the input string and return a new string with the order of characters reversed.

Constraints:

  • You must not use any built-in reverse methods (like Array.prototype.reverse() in JavaScript).
  • The input will consist of printable ASCII characters.
  • If an empty string is provided, an empty string should be returned.

Expected result

The function should return a string that is the exact reverse of the input string.

For example:

  • Calling reverseString("hello") should return "olleh".
  • Calling reverseString("freeCodeCamp") should return "pmaCedoCeerf".
  • Calling reverseString("123! abc") should return "cba !321".
  • Calling reverseString("") should return "".
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.