Module axum::ws [−][src]
This is supported on crate feature
ws
only.Expand description
Handle websocket connections.
Example
use axum::{prelude::*, ws::{ws, WebSocket}}; let app = route("/ws", ws(handle_socket)); async fn handle_socket(mut socket: WebSocket) { while let Some(msg) = socket.recv().await { let msg = msg.unwrap(); socket.send(msg).await.unwrap(); } }
Websocket handlers can also use extractors, however the first function
argument must be of type WebSocket
:
use axum::{prelude::*, extract::{RequestParts, FromRequest}, ws::{ws, WebSocket}}; use http::{HeaderMap, StatusCode}; /// An extractor that authorizes requests. struct RequireAuth; #[async_trait::async_trait] impl<B> FromRequest<B> for RequireAuth where B: Send, { type Rejection = StatusCode; async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { // Put your auth logic here... } } let app = route("/ws", ws(handle_socket)); async fn handle_socket( mut socket: WebSocket, // Run `RequireAuth` for each request before upgrading. _auth: RequireAuth, ) { // ... }
Modules
Future types.
Structs
A WebSocket message.
A stream of websocket messages.
Service
that upgrades connections to websockets and spawns a task to
handle the stream.
Traits
Trait for async functions that can be used to handle websocket requests.
Functions
Create a new WebSocketUpgrade
service that will call the closure with
each connection.