Crate actix_send_websocket

Source
Expand description

A websocket service for actix-web framework.

§Example:

use actix_web::{get, App, Error, HttpRequest, HttpServer, Responder};
use actix_send_websocket::{Message, WebSocket};

#[get("/")]
async fn ws(ws: WebSocket) -> impl Responder {
    // stream is the async iterator of incoming client websocket messages.
    // res is the response we return to client.
    // tx is a sender to push new websocket message to client response.
    let (mut stream, res, mut tx) = ws.into_parts();

    // spawn the stream handling so we don't block the response to client.
    actix_web::rt::spawn(async move {
        while let Some(Ok(msg)) = stream.next().await {
            let result = match msg {
                // we echo text message and ping message to client.
                Message::Text(string) => tx.text(string),
                Message::Ping(bytes) => tx.pong(&bytes),
                Message::Close(reason) => {
                    let _ = tx.close(reason);
                    // force end the stream when we have a close message.
                    break;
                }
                // other types of message would be ignored
                _ => Ok(()),
            };
            if result.is_err() {
                // end the stream when the response is gone.
                break;
            }
        }   
    });

    res
}

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

§Features

FeatureDescriptionExtra dependenciesDefault
defaultThe same as send featuretokio with sync feature enabledyes
sendEnable websocket sink with Send markertokio with sync feature enabledyes
no-sendweboscoekt on local thread onlynoneno

Structs§

CloseReason
Reason for closing the connection
Codec
WebSockets protocol codec
DecodeStream
EncodeStream
WebSocket
extractor type for websocket.
WebSocketSender
WsConfig
config for WebSockets.

Enums§

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

Functions§

handshake
Prepare WebSocket handshake response.
handshake_with_protocols
Prepare WebSocket handshake response.
split_stream
split stream into decode/encode streams and a sender that can send item to encode stream.