#actix #ws #actors #websockets

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
Download history 201/week @ 2022-03-13 200/week @ 2022-03-20 200/week @ 2022-03-27 219/week @ 2022-04-03 193/week @ 2022-04-10 117/week @ 2022-04-17 171/week @ 2022-04-24 174/week @ 2022-05-01 226/week @ 2022-05-08 223/week @ 2022-05-15 88/week @ 2022-05-22 114/week @ 2022-05-29 214/week @ 2022-06-05 97/week @ 2022-06-12 118/week @ 2022-06-19 149/week @ 2022-06-26

593 downloads per month

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

~15–23MB
~521K SLoC