actix-ws 0.4.0

WebSockets for Actix Web, without actors
Documentation

actix-ws

WebSockets for Actix Web, without actors.

crates.io Documentation Version MIT or Apache 2.0 licensed Dependency Status Download Chat on Discord

Example

use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Responder};
use actix_ws::Message;

async fn ws(req: HttpRequest, body: web::Payload) -> actix_web::Result<impl Responder> {
    let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;

    actix_web::rt::spawn(async move {
        while let Some(Ok(msg)) = msg_stream.recv().await {
            match msg {
                Message::Ping(bytes) => {
                    if session.pong(&bytes).await.is_err() {
                        return;
                    }
                }
                Message::Text(msg) => println!("Got text: {msg}"),
                _ => break,
            }
        }

        let _ = session.close(None).await;
    });

    Ok(response)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .route("/ws", web::get().to(ws))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await?;

    Ok(())
}

Typed Messages (Optional)

Enable the serde-json feature to send/receive typed messages using serde_json.

See examples/json.rs and run it with:

cargo run -p actix-ws --features serde-json --example json

WebSocket Sub-Protocols

Use handle_with_protocols when your server supports one or more Sec-WebSocket-Protocol values.

let (response, session, msg_stream) = actix_ws::handle_with_protocols(
    &req,
    body,
    &["graphql-transport-ws", "graphql-ws"],
)?;

When there is an overlap, the first protocol offered by the client that the server supports is returned in the handshake response.

Resources

License

This project is licensed under either of

at your option.