my implementation of websockets for actix-web
Go to file
2020-09-27 12:45:58 -05:00
examples/chat Fix build 2020-04-25 14:23:35 -05:00
src clippy 2020-04-25 20:57:47 -05:00
.gitignore Restructure repo 2020-04-25 13:19:09 -05:00
Cargo.toml Stable deps 2020-09-27 12:45:58 -05: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 cargo.toml, readme 2020-04-25 14:21:17 -05:00

Actix WS

websockets for the Actix Runtime without actors

Usage

# Cargo.toml
anyhow = "1.0"
actix-rt = "1.1.0"
actix-web = "3.0.0-alpha.1"
actix-ws = "0.1.0-alpha.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_rt::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.