WebSocket type
Learn how the WebSocket type works in Axum, how to read messages with recv, send replies with send, and run the loop that keeps a connection alive
WebSocket is the open connection itself. It is the value the upgrade callback receives, and it is the only thing the callback needs: it reads messages from the client, writes messages back to the client, and tells the callback when the connection is over. A handler never builds a WebSocket by hand, and a program never stores one for later use outside the callback. It arrives from on_upgrade, it lives for exactly one connection, and it is gone when the callback returns.
Where This Fits
The previous page ended with the upgrade: the extractor checked the request and on_upgrade answered 101. This page picks up the value that arrives after that answer, the socket, and explains what it can do. The extractor is the gate, the socket is the conversation, and everything from here on is about the conversation.
Think of a telephone handset. The upgrade is the dialling and the ringing, and the socket is the handset once the other side has picked up. You speak into it, you listen through it, and when the other side hangs up, the line goes quiet. The socket is the handset, not the phone call as a whole, and your code holds it for as long as the call lasts.
The Smallest Working Version
This server upgrades a connection, reads one message, and sends it back with a prefix. The prefix proves the reply came from the server, not from the client itself.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"
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 };
if let Message::Text(text) = msg {
let reply = format!("server got: {text}");
if socket.send(Message::text(reply)).await.is_err() {
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. A client built on tokio-tungstenite connects, sends hello, and receives the prefixed reply. The live run below comes from the scratch project used to verify this chapter, with the server on port 3001 and the client sending two messages:
client: handshake status 101 Switching Protocols
client received: Text(Utf8Bytes(b"hello"))
client received: Text(Utf8Bytes(b"second message"))
The client output shows the plain echo version of this server, which sends each message back unchanged. The prefixed version above answers hello with server got: hello instead, and the shape of the run is the same: 101, then one reply per message, in order.
Working Setup:
If the client handshake prints 101 and each sent message comes back, the socket loop is running. If the client connects and receives nothing, the callback is probably returning early, and the mistakes section below covers the usual causes.
Understanding the Socket Line by Line
The socket callback has four moving parts, and each one is a method on WebSocket or a fact about the loop.
Receiving with recv
while let Some(msg) = socket.recv().await {
recv waits for the next message and returns Option<Result<Message, axum::Error>>, which is three outcomes in one type. Some(Ok(msg)) means a message arrived. Some(Err(error)) means the connection broke while reading, for example the client vanished mid-message. None means the stream closed cleanly, because the client closed it or the server did. The while let Some(msg) shape keeps looping on the first two outcomes and stops on None, and the let Ok(msg) = msg else { return } line inside the loop returns from the callback on the error outcome. That is the whole receive discipline: loop while there are messages, leave when there are none or when reading fails.
Sending with send
if socket.send(Message::text(reply)).await.is_err() {
return;
}
send takes one Message and delivers it to the client, returning a Result. It fails when the client is gone, so the is_err check returns from the callback in that case, which ends the connection cleanly instead of looping forever on a dead socket. A send does not wait for the client to answer, and it does not wait for the client to read the message. It hands the message to the underlying transport and returns.
Why the socket is mut
async fn handle_socket(mut socket: WebSocket) {
Both recv and send take &mut self, a mutable borrow, because reading advances the stream and writing changes its state. The mut on the argument is what allows those calls. A socket passed without mut fails to compile at the first recv, with an error about a mutable borrow. The same applies to a socket received through a closure: the closure must bind it as mut, as in |mut socket| async move { ... }.
Why the loop returns instead of breaking
The callback returns (), nothing, so return ends the callback and the background task with it. break would also leave the loop, but then the function would fall through to whatever comes after the loop, which in these examples is the end of the function anyway. return is used inside the loop because it works from any depth, including inside a match arm or an if let, where break would only leave the innermost construct. The effect is the same here: the socket is dropped, the connection closes, and the task ends.
The Concept Behind the Socket
A WebSocket is a stream of messages and a sink for messages in one value. "Stream" means values arrive over time and the program pulls them out one by one with recv. "Sink" means the program pushes values in with send. The two directions are independent: the server can send a greeting before the client sends anything, and the client can send three messages while the server is still working on the first one. The socket keeps the two directions separate internally, which is why the callback can send inside the receive loop without deadlocking.
The socket also carries the subprotocol the upgrade chose, readable with protocol(), which returns Option<&HeaderValue>, the chosen name or nothing. It carries no other state the callback needs to manage. There is no manual buffer to drain, no frame to assemble, and no handshake left to finish. The protocol work, masking, framing, and the automatic pong reply, happens underneath, inside tokio-tungstenite.
The Socket Is One Connection, Not the Server:
A WebSocket belongs to a single client. The server creates one per connection, and each one has its own loop, its own task, and its own lifetime. State shared between connections, such as a chat room or a user list, lives outside the socket, in a value the handler passes into the callback, and the broadcast page shows that shape in full.
Why recv and send Are the Only Two Methods You Need at First
WebSocket also implements the Stream and Sink traits from futures-util, which is why recv is a thin wrapper over the stream and send is a thin wrapper over the sink. Those traits add the whole combinator library: split, map, filter, and more. The direct methods are enough for the common shapes, a loop that echoes, a loop that broadcasts, and a loop that reacts to each message. The trait methods become useful when one task must read while another writes, which needs the split form, and that shape has its own treatment on the splitting page. Starting with recv and send keeps the loop readable, and the loop is where most WebSocket bugs live.
A Richer Example With a Command Loop
A realistic socket loop does more than echo. It reads each message, decides what it means, and answers differently. This example treats each text message as a command: ping gets pong, time gets the current time in seconds, and anything else gets an echo with a prefix:
use std::time::{SystemTime, UNIX_EPOCH};
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 };
let Message::Text(text) = msg else { continue };
let reply = match text.as_str() {
"ping" => "pong".to_string(),
"time" => {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
format!("now: {now}")
}
other => format!("echo: {other}"),
};
if socket.send(Message::text(reply)).await.is_err() {
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();
}
The let Message::Text(text) = msg else { continue } line skips every message that is not text, which includes binary frames and the control frames covered on their own pages. continue goes back to the top of the loop and waits for the next message, instead of returning and closing the connection. The match on text.as_str() compares the text with the two commands and falls through to the echo for anything else. A client sending ping, then time, then hello receives pong, then now: 1794712345 with the real current time, then echo: hello.
Skipping a Message Is Not the Same as Closing:
continue ignores one message and keeps the connection open. return ends the connection. A loop that returns on a message it does not understand closes the socket for every client that sends an unexpected frame, which is the most common way a "the server drops my connection" bug is born. Skip what you cannot handle, close only when the connection itself is over.
Variations
Greeting the client first
The socket can send before it receives, which is how a server greets a new connection or sends the current state:
async fn handle_socket(mut socket: WebSocket) {
let _ = socket.send(Message::text("welcome to the server")).await;
let _ = socket.send(Message::text("send ping, time, or any text")).await;
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if socket.send(msg).await.is_err() {
return;
}
}
}
The two sends run before the loop starts, and the client receives both greetings before it sends anything. The let _ = ignores a send failure, because a client that disconnects during the handshake leaves no one to greet, and there is nothing useful to do with the error at that point.
Reading without replying
Not every loop answers. A logging server reads each message, prints it, and sends nothing back:
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
println!("received: {msg:?}");
}
println!("client left");
}
The final println! runs when the loop ends, which is when recv returns None. That line is the simplest form of disconnect logging, and it is useful in every example on this page: a connection that ends quietly is hard to debug, and one line of output marks the moment it happened.
Checking whether the socket has ended
WebSocket implements FusedStream from futures-util, which adds is_terminated(), a method that returns true when the stream has ended and will never produce another message:
use futures_util::stream::FusedStream;
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if socket.send(msg).await.is_err() {
return;
}
}
println!("terminated: {}", socket.is_terminated());
}
The import matters: is_terminated comes from the FusedStream trait, so calling it without importing the trait fails to compile with an error that names the trait and suggests the import. The method is rarely needed inside the loop, because the loop itself ends when the stream ends, but it is useful after the loop, in cleanup code that must know whether the socket ended or is still alive.
Reading through the Stream trait
recv is the direct way to read, and it is not the only way. WebSocket also implements Stream from futures-util, the trait for values that arrive one at a time over time, so socket.next().await reads the next message exactly like recv does:
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use futures_util::StreamExt;
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.next().await {
let Ok(msg) = msg else { return };
if let Message::Text(text) = msg {
println!("stream got: {}", text.as_str());
}
}
}
next comes from the StreamExt trait, so it needs the import, just as is_terminated needs its own trait import. The loop is the same shape as the recv loop, and the messages are the same Result<Message, Error> values. The Stream implementation is what makes the rest of the futures toolbox work on a socket: split turns the socket into a separate sender and receiver, and combinators such as map and filter can transform the message stream before the loop sees it. For a plain echo, recv is simpler, because it needs no import, and the Stream form is for the moment a socket must behave like any other stream in the futures ecosystem.
Passing extra data into the callback
The callback is a closure, so it can capture values from the handler, including state. The upgrade page shows the shape with State, and the same shape works with any value the handler owns:
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
let greeting = "welcome".to_string();
ws.on_upgrade(|socket| handle_socket(socket, greeting))
}
async fn handle_socket(mut socket: WebSocket, greeting: String) {
let _ = socket.send(Message::text(greeting)).await;
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if socket.send(msg).await.is_err() {
return;
}
}
}
The closure |socket| handle_socket(socket, greeting) moves greeting into the callback, which is why the closure must own it. The handler returns immediately after on_upgrade, so anything the callback needs must be moved in at that point. A value that cannot move, such as a reference to a local variable, fails to compile, because the callback outlives the handler by an unknown amount of time.
A Plain Text Diagram of the Socket Loop
The loop has two exits, and both are normal:
callback receives the WebSocket
|
v
recv waits for a message
|
+-- Some(Ok(msg)) --> handle it, maybe send a reply --> back to recv
|
+-- Some(Err(_)) --> return, connection broke
|
+-- None --> return, stream closed cleanly
A send failure inside the handling step is a third exit, and it also returns. Every exit drops the socket and ends the background task, and none of them is an error worth panicking over.
Testing It
The test below runs the command loop against a real client. It connects, sends ping and expects pong, sends hello and expects the echo, and then closes. It needs tokio-tungstenite as a dev-dependency:
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
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 };
let Message::Text(text) = msg else { continue };
let reply = match text.as_str() {
"ping" => "pong".to_string(),
other => format!("echo: {other}"),
};
if socket.send(Message::text(reply)).await.is_err() {
return;
}
}
}
#[tokio::test]
async fn command_loop_answers_ping_and_echo() {
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("ping".into())).await.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(msg, ClientMessage::Text("pong".into()));
ws.send(ClientMessage::Text("hello".into())).await.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(msg, ClientMessage::Text("echo: hello".into()));
ws.close(None).await.unwrap();
}
Run it with:
cargo test --test socket_test
test command_loop_answers_ping_and_echo ... ok
The test follows the same pattern as the upgrade test: bind to port 0, spawn the server, connect a real client, and assert on the replies. The assertions compare whole messages, so a wrong prefix or a missing reply fails the test instead of passing silently.
Common Beginner Mistakes
Forgetting mut on the socket
// Wrong - recv and send need a mutable borrow
async fn handle_socket(socket: WebSocket) {
while let Some(msg) = socket.recv().await {
The compiler rejects this with an error about recv needing &mut self. The fix is mut socket in the argument list. The same error appears for a socket bound inside a closure without mut. It is the most common first error with this type, and it always means the same thing: the socket changes as it is used, so the binding must allow change.
Unwrapping the recv result
// Wrong - a single broken read panics the whole connection task
while let Some(msg) = socket.recv().await {
let msg = msg.unwrap();
A client that disconnects uncleanly makes recv yield an error, and unwrap turns that into a panic, which kills the background task and prints a panic message for an event that is completely normal. The fix is the let Ok(msg) = msg else { return } shape, which treats a read error as the end of the connection. Reserve unwrap for errors that should never happen, and a client leaving is not one of them.
Ignoring the send result in the loop
// Wrong - the loop keeps running after the client is gone
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let _ = socket.send(msg).await;
}
Ignoring the send result does not crash anything, but it hides the moment the client leaves. The loop keeps waiting on recv, which will return None soon enough, so the connection does end, but the server does one extra wait for no reason. Checking the result and returning early is cleaner, and it matters more in loops that do work between messages, where a dead client would otherwise pay for work nobody receives.
Returning on a message the loop does not understand
// Wrong - an unknown message closes the connection
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { return };
The else { return } on a non-text message ends the whole connection the first time a client sends a binary frame, or a ping, or anything else. The fix is else { continue }, which skips that one message and waits for the next. The distinction between "this message is not for me" and "this connection is over" is the difference between continue and return, and mixing them up is the most common logic bug in a socket loop.
Storing the socket for later
// Wrong - the socket cannot outlive the callback
static mut SOCKET: Option<WebSocket> = None;
A WebSocket cannot be stored in a global or returned from the callback, because it is tied to the connection task and to the socket's own lifetime. The fix is to do the work inside the callback, or to pass the socket into a spawned task that lives as long as the connection, which is the shape the broadcast page uses. Anything shared between connections goes in state, not in a stored socket.
Final Complete Example
Here is everything from this page put together: the command loop with a greeting, the disconnect log, and the test that proves the commands work.
use std::time::{SystemTime, UNIX_EPOCH};
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) {
let _ = socket.send(Message::text("welcome to the server")).await;
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let Message::Text(text) = msg else { continue };
let reply = match text.as_str() {
"ping" => "pong".to_string(),
"time" => {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
format!("now: {now}")
}
other => format!("echo: {other}"),
};
if socket.send(Message::text(reply)).await.is_err() {
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 socket_test
cargo run
Summary
The WebSocket type is a small surface with a large job: recv pulls messages out one by one, send pushes replies back, and the loop around them decides what the connection means. The socket is born in on_upgrade, lives for one connection, and ends when the loop returns, and every exit from that loop is a normal ending, not an error. The habit to carry forward is to treat the loop as the connection: a message the loop skips is a message ignored, a message the loop returns on is a connection closed, and the difference between the two is one keyword. The next piece is the messages themselves, the five shapes a recv can return and what each one means.