my implementation of websockets for actix-web
Find a file
2022-03-09 23:21:18 -06:00
examples/chat Update to latest actix web 2022-03-09 12:28:11 -06:00
src Remove pin-project-lite, it wasn't needed 2022-03-09 23:21:18 -06:00
.gitignore Restructure repo 2020-04-25 13:19:09 -05:00
Cargo.toml Remove pin-project-lite, it wasn't needed 2022-03-09 23:21:18 -06:00
LICENSE-APACHE Update cargo.toml, readme 2020-04-25 14:21:17 -05:00
LICENSE-MIT Update cargo.toml, readme 2020-04-25 14:21:17 -05:00
README.md Update readme 2022-03-09 12:30:22 -06:00

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.