1 unstable release

0.3.0 Oct 19, 2023
0.2.5 Oct 19, 2023

#170 in WebSocket

Download history 8/week @ 2024-02-13 45/week @ 2024-02-20 42/week @ 2024-02-27 9/week @ 2024-03-05 16/week @ 2024-03-12 20/week @ 2024-03-19 33/week @ 2024-03-26 25/week @ 2024-04-02 13/week @ 2024-04-09 5/week @ 2024-04-16

85 downloads per month

MIT/Apache

19KB
258 lines

Actix WS (Next Gen)

WebSockets for Actix Web, without actors.

Usage

# Cargo.toml
anyhow = "1"
actix-web = "4"
actix-ws-ng = "0.3"
// 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–31MB
~529K SLoC