Module actix_web::ws [] [src]

WebSocket support for Actix

To setup a WebSocket, first do web socket handshake then on success convert Payload into a WsStream stream and then use WsWriter to communicate with the peer.

Example

extern crate actix;
extern crate actix_web;

use actix::*;
use actix_web::*;

// WebSocket Route
struct WsRoute;

impl Actor for WsRoute {
    type Context = HttpContext<Self>;
}

impl Route for WsRoute {
    type State = ();

    fn request(req: &mut HttpRequest,
               payload: Payload, ctx: &mut HttpContext<Self>) -> RouteResult<Self>
    {
        // WebSocket handshake
        match ws::handshake(&req) {
            Ok(resp) => {
                // Send handshake response to peer
                ctx.start(resp);
                // Map Payload into WsStream
                ctx.add_stream(ws::WsStream::new(payload));
                // Start ws messages processing
                Reply::async(WsRoute)
            },
            Err(err) =>
                Reply::reply(err)
        }
    }
}

// Define Handler for ws::Message message
impl StreamHandler<ws::Message> for WsRoute {}

impl Handler<ws::Message> for WsRoute {
    fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>)
              -> Response<Self, ws::Message>
    {
        match msg {
            ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg),
            ws::Message::Text(text) => ws::WsWriter::text(ctx, &text),
            ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin),
            _ => (),
        }
        Self::empty()
    }
}

fn main() {}

Structs

WsStream

Maps Payload stream into stream of ws::Message items

WsWriter

WebSocket writer

Enums

CloseCode

Status code used to indicate why an endpoint is closing the WebSocket connection.

Message

WebSocket Message

Functions

handshake

Prepare WebSocket handshake response.