rustapi-ws: The Live Wire
Lens: “The Live Wire” Philosophy: “Real-time, persistent connections made simple.”
The WebSocket Extractor
Upgrading an HTTP connection to a WebSocket uses the standard extractor pattern:
#![allow(unused)]
fn main() {
async fn ws_handler(
ws: WebSocket,
) -> impl IntoResponse {
ws.on_upgrade(handle_socket)
}
}
Architecture
We recommend an Actor Model for WebSocket state.
- Each connection spawns a new async task (the actor).
- Use
tokio::sync::broadcastchannels for global events (like chat rooms). - Use
mpscchannels for direct messaging.