Module ws

Source
Expand description

Websocket integration.

§Examples

use actix::{Actor, StreamHandler};
use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;

/// Define Websocket actor
struct MyWs;

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}

#[get("/ws")]
async fn websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    ws::start(MyWs, &req, stream)
}

const MAX_FRAME_SIZE: usize = 16_384; // 16KiB

#[get("/custom-ws")]
async fn custom_websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    // Create a Websocket session with a specific max frame size, and protocols.
    ws::WsResponseBuilder::new(MyWs, &req, stream)
        .frame_size(MAX_FRAME_SIZE)
        .protocols(&["A", "B"])
        .start()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
            App::new()
                .service(websocket)
                .service(custom_websocket)
        })
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

Structs§

CloseReason
Reason for closing the connection
WebsocketContext
Execution context for WebSockets actors
WsResponseBuilder
Builder for Websocket session response.

Enums§

CloseCode
Status code used to indicate why an endpoint is closing the WebSocket connection.
Frame
A WebSocket frame.
HandshakeError
WebSocket handshake errors
Message
A WebSocket message.
ProtocolError
WebSocket protocol errors.

Functions§

handshake
Prepare WebSocket handshake response.
handshake_with_protocols
Prepare WebSocket handshake response.
start
Perform WebSocket handshake and start actor.
start_with_addrDeprecated
Perform WebSocket handshake and start actor.
start_with_protocolsDeprecated
Do WebSocket handshake and start ws actor.