#actix

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

#503 in HTTP server

Download history 861/week @ 2023-08-12 883/week @ 2023-08-19 850/week @ 2023-08-26 1077/week @ 2023-09-02 1104/week @ 2023-09-09 921/week @ 2023-09-16 985/week @ 2023-09-23 1380/week @ 2023-09-30 1461/week @ 2023-10-07 1294/week @ 2023-10-14 1620/week @ 2023-10-21 2116/week @ 2023-10-28 2362/week @ 2023-11-04 2761/week @ 2023-11-11 1869/week @ 2023-11-18 1846/week @ 2023-11-25

9,187 downloads per month
Used in 4 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–29MB
~524K SLoC