WebSockets with Axum
Use case
You need real-time bidirectional communication: chat, live updates, or streaming. Axum has built-in WebSocket support via the ws feature. You upgrade the HTTP connection and then send/receive messages.
In C#: Like SignalR or raw WebSockets with HttpContext.WebSockets.AcceptWebSocketAsync. In Rust, axum provides an extractor and a stream of messages.
WebSocket handler
Use axum::extract::ws::WebSocketUpgrade and axum::extract::ws::WebSocket. Call upgrade.on_upgrade(|socket| async move { ... }) to run your WebSocket logic when the client upgrades.
use axum::extract::ws::{WebSocket, WebSocketUpgrade};
use futures_util::{SinkExt, StreamExt};
async fn ws_handler(ws: WebSocketUpgrade) -> axum::response::Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
while let Some(Ok(msg)) = receiver.next().await {
// echo or broadcast
let _ = sender.send(msg).await;
}
}In C#: Like accepting the WebSocket and then reading/writing in a loop. In Rust you use async streams (futures_util).
Sending and receiving
Split the socket into sender and receiver with .split(). Use receiver.next().await to receive; use sender.send(message).await to send. Message types include Text, Binary, Close. Use futures_util::StreamExt and SinkExt for the combinators.
In C#: Like ReceiveAsync and SendAsync on the WebSocket.
Key takeaway
Use WebSocketUpgrade extractor and .on_upgrade(handle_socket). In the handler, split the socket and use async streams to receive and send. Enable the ws feature on axum and add futures_util for StreamExt/SinkExt.