Skip to main content

start

Function start 

Source
pub async fn start<S>(
    req: &HttpRequest,
    subprotocol: Option<&str>,
    f: impl IntoService<S, WsSink, Frame>,
) -> Result<(), WsError<S::Error>>
where S: Service<WsSink, Frame, Res = Option<Message>> + 'static, S::Error: Debug,
Expand description

Start websocket service handling Frame messages with automatic control/stop logic, including the chosen subprotocol in the response.

If subprotocol is Some, the Sec-Websocket-Protocol header will be included in the response with the chosen protocol. The protocol must be a valid HTTP token offered by the client. If None, the header is omitted.

If the handshake fails for an upgrade request, the handshake error response is sent and the connection is closed.

ยงExample

use ntex::web::{self, HttpRequest, ws};

async fn service(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
    // handle incoming frames
    Ok(None)
}

async fn handler(req: HttpRequest) {
    let chosen = ws::subprotocols(&req)
        .find(|p| *p == "graphql-ws" || *p == "graphql-transport-ws");

    if let Err(err) = ws::start(&req, chosen, service).await {
        eprintln!("WebSocket error: {err:?}");
    }
}

let app = web::App::default().route("/ws", web::get().to(handler));