pub async fn start<S>(
req: &HttpRequest,
subprotocol: Option<&str>,
f: impl IntoService<S, WsSink, Frame>,
) -> Result<(), WsError<S::Error>>Expand description
Start websocket service handling Frame messages, 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.
With the compress feature, the permessage-deflate extension is accepted
if it is enabled with
HttpServiceConfig::set_ws_deflate().
Control frames are passed to the service too. If it returns None for
a ping and hasn’t sent a pong through a sink meanwhile, a pong with the
same payload is sent. If it returns None for the peer’s close frame,
a close echoing the peer’s code is sent. No automatic reply is sent once
a close message has been sent through a sink. After the peer’s close frame
is handled, the connection is closed. Dispatcher control and stop events
are handled by start(), a service error sends a close frame with
CloseCode::Away.
§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));