Skip to main content

Module websocket

Module websocket 

Source
Expand description

WebSocket endpoints (feature websocket)

use ullun::prelude::*;
use ullun::websocket::{Message, WebSocket};

App::new()
    .ws("/echo/{room}", |req: Request, mut socket: WebSocket| async move {
        let room = req.params.get_opt("room").unwrap_or("lobby").to_string();
        let _ = socket.send_text(format!("welcome to {room}")).await;
        while let Some(Ok(msg)) = socket.recv().await {
            match msg {
                Message::Text(t) => { let _ = socket.send_text(t).await; }
                Message::Close => break,
                _ => {}
            }
        }
    })
    .run("127.0.0.1:3000")
    .await
    .unwrap();

The handshake is validated (version 13, key, Connection/Upgrade) and, because browsers do not apply the same-origin policy to WebSockets, a cross-site Origin is rejected with 403 unless it is listed in WsOptions::allowed_origins. Clients without an Origin header (native apps, CLI tools) are accepted; authenticate them in middleware.

Structs§

WebSocket
An upgraded connection
WsOptions
Per-endpoint settings

Enums§

Message
A WebSocket message