Skip to main content

Module websocket

Module websocket 

Source
Expand description

WebSocket support (RFC 6455). Behind the websocket feature.

A route handler that wants to serve a WebSocket validates the request as usual (origin, auth, subprotocol — whatever it needs), then returns upgrade(...) instead of an ordinary reply. The server completes the handshake (101 Switching Protocols), upgrades the connection, and runs the closure you supplied on the resulting WebSocket (a Stream of incoming Messages and a Sink for outgoing ones).

use actus::prelude::*;
use futures_util::{SinkExt, StreamExt};

pub async fn echo(&self, _params: &Params) -> Reply {
    Ok(actus::ws::upgrade(|mut socket| async move {
        while let Some(Ok(msg)) = socket.next().await {
            if msg.is_text() || msg.is_binary() {
                let _ = socket.send(msg).await;
            }
        }
    }))
}

Mount it like any other route (GET "echo" => echo()). If the request reaching such a handler isn’t actually a WebSocket handshake, the server responds 426 Upgrade Required instead of attempting the upgrade.

§Timing of the upgrade capture

The server captures OnUpgrade (and derives Sec-WebSocket-Accept) for any request whose method/headers look like an RFC 6455 handshake — before middleware or routing runs. That means a handshake-shaped request that ends up short-circuited by middleware, rejected on auth, or routed to a non-WS handler still pays the small cost of capturing the upgrade future; the captured OnUpgrade is then dropped harmlessly (hyper handles a dropped upgrade future). This shape is deliberate: it keeps the upgrade capture out of the handler’s hot path and avoids threading a “give me the upgrade now” callback through the reply machinery.

Enums§

Message
Re-export of tungstenite’s message type — text / binary / ping / pong / close frames. An enum representing the various forms of a WebSocket message.

Functions§

upgrade
Return this from a route handler to turn the response into a WebSocket upgrade. handler runs on the upgraded connection after the handshake. See the module docs.

Type Aliases§

WebSocket
A server-side WebSocket connection: a Stream of incoming Messages and a Sink for outgoing ones. Obtained inside the closure passed to upgrade.