WebSocket echo server

Learn how to build a complete WebSocket echo server in Axum that answers every message in kind, with a live client run and tests

An echo server is a WebSocket server that sends every message straight back to the client that sent it. It is the smallest server that proves the whole path works: the upgrade, the loop, the reading, the writing, and the close. It is also the base every later server in this chapter grows from, because a chat server is an echo server that forwards to others, and a broadcast server is an echo server that forwards to everyone. Build the echo first, prove it with a real client, and the rest is a change to one line.

Where This Fits

The previous eight pages introduced the pieces one at a time: the flag, the extractor, the socket, the five message kinds, text, binary, ping and pong, and the close frame. This page puts them together into one complete, runnable server. Nothing here is new, and that is the point: the echo server is the proof that the pieces fit.

Think of an echo server like a mountain that repeats your shout. You shout a word, the mountain sends the same word back, and the repetition proves the valley carries sound both ways. The server is the mountain, and the client's message is the shout.

The Smallest Working Version

This is the complete echo server. It upgrades one route, loops on the socket, and sends each data message back unchanged, whatever its kind. Control frames are not echoed: a ping is left to the automatic pong reply, and a close ends the loop.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};

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

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        match msg {
            Message::Text(_) | Message::Binary(_) => {
                if socket.send(msg).await.is_err() {
                    return;
                }
            }
            Message::Close(_) => return,
            _ => {}
        }
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/ws", get(ws_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run it with cargo run. The server prints the startup line and waits. The echo loop is ten lines long, and it is the whole server: read a message, send it back if it is data, end the loop if it is a close, and ignore the rest.

Working Setup:

If cargo run starts without errors and the server prints its startup line, the echo server is running. The proof that it echoes comes from the client run below, not from the server output, because an echo server prints nothing on its own.

The Live Run With a Real Client

A server that only prints a startup line proves nothing about the echo, so this page proves it with a real client: a small Rust program built on tokio-tungstenite 0.29.0, the same WebSocket implementation Axum uses underneath. The client connects, sends two text messages, sends five binary bytes, sends a ping, and closes. The client code is shown in full, because a WebSocket server cannot be tested without a WebSocket client, and this client is the one used for every live run in this chapter.

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
src/bin/client.rs
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};

#[tokio::main]
async fn main() {
    let url = "ws://127.0.0.1:3000/ws";
    let (mut ws, response) = connect_async(url).await.unwrap();
    println!("handshake status {}", response.status());
    ws.send(Message::Text("hello".into())).await.unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    println!("received: {msg:?}");
    ws.send(Message::Text("second message".into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    println!("received: {msg:?}");
    ws.send(Message::Binary(vec![0u8, 1, 2, 3, 255].into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    println!("received binary: {msg:?}");
    ws.send(Message::Ping(b"hello".to_vec().into())).await.unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    println!("received after ping: {msg:?}");
    ws.close(None).await.unwrap();
}

Run the server in one terminal and the client in another. The client output, observed against the echo server in the verification project, is:

client: handshake status 101 Switching Protocols
client received: Text(Utf8Bytes(b"hello"))
client received: Text(Utf8Bytes(b"second message"))
client received binary: Binary(b"\0\x01\x02\x03\xff")
client received after ping: Pong(b"hello")

Each line is one round trip. The handshake is 101. The two text messages come back unchanged. The five binary bytes come back unchanged, including the zero byte and the 255 byte. The ping comes back as a pong with the same payload, sent automatically by the server's WebSocket layer even though the echo loop never sees a pong to send. The close at the end is the one rough edge of the plain echo loop. The client sent its close frame, and the server returned on it without draining, so the socket was dropped before the queued close reply was flushed:

client sent close frame (code 1000, reason done)
client stream error after close: WebSocket protocol error: Connection reset without closing handshake

The client expected a close reply and got a reset instead, because the reply was queued and never left. The close frame page explains why: the reply only leaves when the socket is read again, and the plain loop never reads again. The richer version below fixes this with the drain loop, and its close is clean. The plain echo is correct for text, binary, and ping, and the drain is the correction for close.

The server side of the same run prints the messages as they arrive, from a logging version of the loop:

server got text: hello
server got text: second message
server got binary: 5 bytes
server got ping (should not happen, auto pong): 5 bytes
server got text: after ping
server got close: Some((1000, "done"))

The ping line is the most interesting. The loop received the ping and logged it, and the client still received its pong, which proves the pong was sent by the layer underneath, not by the loop. The close line shows code 1000, the normal closure, with the reason done, which the client sent. The echo server answers a close by echoing it, which is a valid close reply, and the connection ends cleanly after it.

Understanding the Echo Loop Line by Line

The loop is short, and each line earns its place.

The receive

while let Some(msg) = socket.recv().await {

recv waits for the next message. Some means a message arrived, and None means the stream ended, so the loop stops. The while let shape is the standard loop for a stream: keep going while there is a next item, stop when there is not.

The error check

let Ok(msg) = msg else { return };

recv returns an Option<Result<Message, Error>>, so msg here is a Result. The let Ok(msg) = msg else { return } shape unwraps the success case and returns from the callback on the error case. A read error means the connection broke, and there is nothing left to echo to, so returning is the correct ending. This line is the reason the loop never panics on a client that disappears mid-message.

The echo itself

match msg {
    Message::Text(_) | Message::Binary(_) => {
        if socket.send(msg).await.is_err() {
            return;
        }
    }
    Message::Close(_) => return,
    _ => {}
}

The match sorts the message by kind before anything is sent. Text and binary are data, and they are sent back unchanged, with the whole msg moved into send, so the reply has exactly the kind and payload the client sent. A close frame ends the loop with return, because no further messages will arrive on that connection. Ping and pong fall into the catch-all arm and are ignored, because the pong reply is automatic and a ping needs no answer from the handler. The send fails when the client is gone, so the is_err check returns from the callback in that case, which ends the connection instead of looping on a dead socket.

The Concept Behind Echo

An echo server is the "hello world" of a bidirectional protocol, and it earns that place because it tests everything at once. The upgrade must work, or the client never connects. The loop must read, or nothing arrives. The loop must write, or nothing comes back. The close must be handled, or the connection hangs. A server that echoes correctly has a working upgrade, a working loop, and a working close, and a server that fails any of those fails the echo. That is why every WebSocket tutorial starts here, and why every later server in this chapter is measured against it: if the echo works and the chat does not, the bug is in the forwarding, not in the connection.

Why the Echo Sends Only Data Messages

Sending the whole msg back works for data, and it fails for control frames, so the loop sorts first. The failure was verified live: a loop that echoes every message, including ping, answers a ping with the ping itself, and the client then receives its own ping back, followed by the automatic pong, followed by a second pong, which is the echo of the pong the client sent in answer to the echoed ping. One ping becomes three messages, and the extra round trips repeat for every ping. A loop that echoes a close frame is worse: it returns before the automatic close reply is flushed, and the client sees a protocol error instead of a clean close. The match avoids both: data is echoed, ping and pong are left to the automatic reply, and close ends the loop. The echo is still the whole message for the kinds where the whole message is the right answer, and the sorting is what keeps the control frames out of it.

Why the Echo Sends the Whole Message

Sending the whole msg back, instead of matching on its kind and rebuilding it, has two benefits for data messages. The first is correctness: the reply has exactly the kind and payload the client sent, with no chance of a translation mistake, such as answering binary with text. The second is brevity: the data arm stays three lines long, and every line is about the connection, not about message kinds. The moment the server must change a message, such as uppercasing text or counting words, the data arm grows a nested match, and the echo becomes a command loop, as the text and message kinds pages show. Until then, the whole-message echo for data is the right shape.

A Richer Example With Logging and a Prefix

A production echo server is rarely silent, and it rarely echoes byte for byte. This version logs every message with its kind and answers text with a prefix, while still echoing binary unchanged:

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};

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

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else {
            println!("read error, ending connection");
            return;
        };
        match msg {
            Message::Text(text) => {
                println!("text: {text}");
                let reply = format!("echo: {text}");
                if socket.send(Message::text(reply)).await.is_err() {
                    return;
                }
            }
            Message::Binary(data) => {
                println!("binary: {} bytes", data.len());
                if socket.send(Message::Binary(data)).await.is_err() {
                    return;
                }
            }
            Message::Ping(data) => {
                println!("ping: {} bytes", data.len());
            }
            Message::Pong(data) => {
                println!("pong: {} bytes", data.len());
            }
            Message::Close(frame) => {
                println!("close: {frame:?}");
                while let Some(msg) = socket.recv().await {
                    match msg {
                        Ok(other) => println!("while draining: {other:?}"),
                        Err(error) => {
                            println!("drain ended: {error}");
                            break;
                        }
                    }
                }
                return;
            }
        }
    }
    println!("client left");
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/ws", get(ws_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The text arm prefixes the reply with echo: , so a client sending hello receives echo: hello. The binary arm echoes the bytes unchanged, because a byte count is not a substitute for the data. The ping and pong arms only log, because the pong reply is automatic. The close arm drains the socket before returning, which is the graceful close from the close frame page: the drain flushes the queued close reply, so the client receives a clean close instead of a reset. The final println! runs when the loop ends without a close frame, which happens when the client disconnects without saying goodbye, and it marks the moment in the log.

The Richer Version Echoes Differently on Purpose:

The richer version answers text with a prefix, so a client can tell the server's reply from its own message. The smallest version answers byte for byte, so a client can check the round trip exactly. Both are echo servers, and the difference is what the test asserts: exact equality for the smallest version, and the prefix for the richer one. Pick the one the test needs.

Variations

Echoing only text

A server that only cares about text skips every other kind with continue:

src/main.rs
async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        let Message::Text(text) = msg else { continue };
        if socket.send(Message::Text(text)).await.is_err() {
            return;
        }
    }
}

The let ... else { continue } line ignores binary, ping, pong, and close frames, and waits for the next message. A close frame is ignored too, which means the loop ends when recv returns None after the close, instead of returning at the close itself. The connection still ends, and the ending is clean, because the drain happens implicitly: recv returning None means the handshake already finished.

Echoing with a delay

A delay between receiving and replying makes the round trip visible, which is useful when demonstrating the server to someone watching the logs:

src/main.rs
async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        if socket.send(msg).await.is_err() {
            return;
        }
    }
}

The sleep is tokio::time::sleep, which pauses only this connection's task while other connections keep running. A std::thread::sleep in the same place would block the whole worker thread and stall other connections, which is the mistake the concurrent connections page explains. The delay is for demonstration only, and a real server answers as fast as it can.

Echoing to a second route

A server can run two echo routes with different behaviour, such as a plain echo on /ws and an uppercase echo on /shout. The whole file is shown, because the second route needs the first route's handler and the imports beside it:

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};

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

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        match msg {
            Message::Text(_) | Message::Binary(_) => {
                if socket.send(msg).await.is_err() {
                    return;
                }
            }
            Message::Close(_) => return,
            _ => {}
        }
    }
}

async fn shout_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        let Message::Text(text) = msg else { continue };
        let reply = text.as_str().to_uppercase();
        if socket.send(Message::text(reply)).await.is_err() {
            return;
        }
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/ws", get(ws_handler))
        .route("/shout", get(|ws: WebSocketUpgrade| async { ws.on_upgrade(shout_socket) }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The /shout route uses an inline closure instead of a named handler, which is a compact way to register a route whose only job is the upgrade. The closure takes the WebSocketUpgrade, calls on_upgrade with the socket function, and returns the response. Both routes share the server, and each connection gets the loop its route names.

Checking the upgrade with curl

A browser is not needed to check the server, and neither is a WebSocket client, for the first check. The curl command with the four upgrade headers proves the route answers 101, and a plain curl without headers proves it answers 400:

curl -i http://127.0.0.1:3000/ws
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 43

Connection header did not include 'upgrade'
curl -i -N \
  -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  -H "Sec-WebSocket-Version: 13" \
  --max-time 3 http://127.0.0.1:3000/ws
HTTP/1.1 101 Switching Protocols
connection: upgrade
upgrade: websocket
sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
date: Sat, 14 Nov 2026 08:48:02 GMT

The 400 proves the extractor runs, and the 101 proves the upgrade works. The echo itself needs a real client, and the client program above is the one to use.

A Plain Text Diagram of the Echo

The message travels from the client to the server and back, unchanged:

client sends Text("hello")
        |
        v
server recv returns Text("hello")
        |
        v
server send delivers Text("hello")
        |
        v
client receives Text("hello")

The diagram has no transformation step, because an echo has none. The richer version adds one step between receiving and sending, where the text is changed, and the diagram grows by exactly that step.

Testing It

The test below runs the whole echo against a real client. It connects, sends text and binary, asserts each comes back unchanged, sends a ping and asserts the pong, and then closes. It needs tokio-tungstenite as a dev-dependency:

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
tower = { version = "0.5", features = ["util"] }
tests/echo_test.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};

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

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else { return };
        match msg {
            Message::Text(_) | Message::Binary(_) => {
                if socket.send(msg).await.is_err() {
                    return;
                }
            }
            Message::Close(_) => return,
            _ => {}
        }
    }
}

#[tokio::test]
async fn echo_round_trip() {
    let app = Router::new().route("/ws", get(ws_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });
    let url = format!("ws://{addr}/ws");
    let (mut ws, response) = connect_async(url).await.unwrap();
    assert_eq!(response.status(), 101);
    ws.send(ClientMessage::Text("hello test".into())).await.unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Text("hello test".into()));
    ws.send(ClientMessage::Binary(vec![0u8, 1, 2, 3, 255].into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Binary(vec![0u8, 1, 2, 3, 255].into()));
    ws.send(ClientMessage::Ping(b"hello".to_vec().into()))
        .await
        .unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Pong(b"hello".to_vec().into()));
    ws.close(None).await.unwrap();
}

#[tokio::test]
async fn plain_http_request_is_rejected() {
    use axum::{body::Body, http::Request};
    use tower::ServiceExt;
    let app = Router::new().route("/ws", get(ws_handler));
    let response = app
        .oneshot(Request::builder().uri("/ws").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), 400);
}

Run them with:

cargo test --test echo_test
test plain_http_request_is_rejected ... ok
test echo_round_trip ... ok

Both tests were run against Axum 0.8.9 and pass. The round trip test is the same exchange as the live run above, with the same messages in the same order, and the rejection test proves the plain request is refused without any network. The round trip test needs tower as a dev-dependency for the second test, because oneshot comes from tower::ServiceExt:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

The Echo Test Closes Without Draining:

The test closes with ws.close(None) and does not read the close reply, which is fine for a test: the test process exits right after, and no one is waiting on the reply. A real client that cares about a clean close reads the reply, as the close frame page shows. A test that asserts on the close reply would need the drain loop on the server side, and the close test on the close frame page is the one that does that.

Common Beginner Mistakes

Echoing every message, including control frames

// Wrong - a ping echoed back causes a ping storm, and a close echoed back is not a clean close
while let Some(msg) = socket.recv().await {
    let Ok(msg) = msg else { return };
    if socket.send(msg).await.is_err() {
        return;
    }
}

This version echoes text and binary correctly, and it mishandles the control frames. A ping comes back as a ping, and the client answers that ping with a pong, which the server echoes back as a pong, so one ping becomes three messages. A close frame is echoed and then the loop returns, which drops the socket before the automatic close reply is flushed, so the client sees a protocol error. The fix is the match from the smallest version: echo text and binary, return on close, and ignore ping and pong. A match is for when the reply differs by kind, and an echo server is exactly that case for control frames, even though its data reply is the whole message.

Unwrapping the recv result

// Wrong - a single broken read panics the connection task
while let Some(msg) = socket.recv().await {
    let msg = msg.unwrap();
    let _ = socket.send(msg).await;
}

A client that disconnects uncleanly makes recv yield an error, and unwrap turns that into a panic. The fix is the let Ok(msg) = msg else { return } shape, which treats a read error as the end of the connection. The echo server is the place this mistake hurts most, because it is the first server a beginner writes, and a panic on disconnect looks like the server is broken when the client simply left.

Echoing before the upgrade finishes

// Wrong - there is no socket to echo on before on_upgrade runs
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    let mut socket = WebSocket::default();
    ws.on_upgrade(handle_socket)
}

There is no WebSocket::default(), and there is no socket before the upgrade. The socket only exists inside the callback that on_upgrade runs, after the 101 is sent. The fix is to do all socket work inside the callback, as every example on this page does. The handler's job ends at on_upgrade, and the callback's job starts there.

Forgetting that the echo loop is per connection

// Wrong - a single global socket cannot serve two clients
static mut SOCKET: Option<WebSocket> = None;

Each connection gets its own socket and its own loop, and a global socket cannot hold two connections at once. The fix is to keep the socket in the callback, where it belongs, and to share state between connections through a value passed into the callback, such as the broadcast channel on the broadcast page. The echo loop is per connection by design, and the sharing happens outside it.

Testing the echo with a browser address bar

A browser address bar sends a plain GET with no upgrade headers, and the server answers 400, which looks like the server is broken. The fix is to test with a WebSocket client, such as the Rust program above, or a browser page that opens a WebSocket in JavaScript. The 400 is the correct answer to a plain request, and it is the proof the extractor is running, not a sign of failure.

Final Complete Example

Here is everything from this page put together: the plain echo server, the logging echo with its prefix and drain, and the tests that prove the round trip.

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};

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

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let Ok(msg) = msg else {
            println!("read error, ending connection");
            return;
        };
        match msg {
            Message::Text(text) => {
                println!("text: {text}");
                let reply = format!("echo: {text}");
                if socket.send(Message::text(reply)).await.is_err() {
                    return;
                }
            }
            Message::Binary(data) => {
                println!("binary: {} bytes", data.len());
                if socket.send(Message::Binary(data)).await.is_err() {
                    return;
                }
            }
            Message::Ping(data) => {
                println!("ping: {} bytes", data.len());
            }
            Message::Pong(data) => {
                println!("pong: {} bytes", data.len());
            }
            Message::Close(frame) => {
                println!("close: {frame:?}");
                while let Some(msg) = socket.recv().await {
                    match msg {
                        Ok(other) => println!("while draining: {other:?}"),
                        Err(error) => {
                            println!("drain ended: {error}");
                            break;
                        }
                    }
                }
                return;
            }
        }
    }
    println!("client left");
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/ws", get(ws_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run the checks with these commands:

cargo check
cargo test --test echo_test
cargo run

Summary

The echo server is ten lines of loop around a whole WebSocket connection, and the live run proved each of those lines: the 101 handshake, the text round trip, the binary round trip with bytes that are not text, the automatic pong, and the close that needs the drain to be clean. The loop sends data messages back whole, because an echo has nothing to change, and it leaves control frames alone, because echoing a ping turns one ping into three messages and echoing a close loses the clean ending. The moment a reply must differ, the data arm grows a nested match, and the server grows into a command loop, a chat room, or a broadcast. The habit to carry forward is to test a WebSocket server with a WebSocket client, because the server's own output never proves the echo, and the client's received messages are the only proof that counts. The next page takes the echo and runs many copies of it at once, one per connection, and explains why they never wait for each other.