Skip to main content
Axum provides full WebSocket support through the ws extractor, enabling real-time bidirectional communication between clients and servers.

Basic WebSocket setup

1

Extract the WebSocket upgrade

Use the WebSocketUpgrade extractor in your handler to initiate the WebSocket handshake:
Use any() instead of get() to support both HTTP/1.1 (which uses GET) and HTTP/2+ (which uses CONNECT) for WebSocket upgrades.
2

Handle the WebSocket connection

Implement the socket handler to send and receive messages:
3

Start the server

Run your application with WebSocket support:

Extracting connection metadata

You can extract HTTP headers, client IP addresses, and other metadata during the upgrade:
Remember to use into_make_service_with_connect_info::<SocketAddr>() when serving to enable ConnectInfo extraction.

Message types

WebSocket messages come in several types:

Concurrent send and receive

Split the socket to send and receive simultaneously:

WebSocket protocols

Negotiate sub-protocols with clients:
You can also check what protocols the client requested:

Configuration options

Customize WebSocket behavior:
  • max_message_size(usize) - Maximum message size (default: 64 MB)
  • max_frame_size(usize) - Maximum frame size (default: 16 MB)
  • read_buffer_size(usize) - Read buffer capacity (default: 128 KB)
  • write_buffer_size(usize) - Write buffer size (default: 128 KB)
  • max_write_buffer_size(usize) - Maximum write buffer size (default: unlimited)
  • accept_unmasked_frames(bool) - Accept unmasked frames from clients (default: false)

Error handling

Handle upgrade failures gracefully:

Full example

Here’s a complete chat server example:
Always handle errors when sending or receiving messages, as clients can disconnect at any time without notice.