#websocket #actix #actors #run-time #actix-web #async #ws

actix-ws

Websockets for the Actix runtime, without Actors

9 releases

0.2.5 Mar 10, 2022
0.2.4 Mar 10, 2022
0.1.0 Sep 27, 2020
0.1.0-alpha.1 May 8, 2020
0.1.0-alpha.0 Apr 25, 2020

#214 in Asynchronous

Download history 1084/week @ 2023-12-16 523/week @ 2023-12-23 870/week @ 2023-12-30 1871/week @ 2024-01-06 1827/week @ 2024-01-13 1189/week @ 2024-01-20 1551/week @ 2024-01-27 1486/week @ 2024-02-03 1533/week @ 2024-02-10 1314/week @ 2024-02-17 1376/week @ 2024-02-24 1634/week @ 2024-03-02 1573/week @ 2024-03-09 1615/week @ 2024-03-16 1957/week @ 2024-03-23 1409/week @ 2024-03-30

6,781 downloads per month
Used in 5 crates

MIT/Apache

15KB
278 lines

Actix WS

websockets for the Actix Runtime without actors

Usage

# Cargo.toml
anyhow = "1.0"
actix-web = "4.0.1"
actix-ws = "0.2.0"
// main.rs
use actix_web::{middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_ws::Message;

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

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

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

    Ok(response)
}

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

    Ok(())
}

License

This project is licensed under either of

at your option.

Dependencies

~17–30MB
~531K SLoC