1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-12-04 20:11:55 +01:00
actix-extras/actix-ws/README.md

75 lines
2.2 KiB
Markdown
Raw Normal View History

2024-07-20 08:23:21 +02:00
# `actix-ws`
2023-11-03 23:49:18 +01:00
> WebSockets for Actix Web, without actors.
2024-01-06 22:08:09 +01:00
<!-- prettier-ignore-start -->
2023-11-03 23:49:18 +01:00
[![crates.io](https://img.shields.io/crates/v/actix-ws?label=latest)](https://crates.io/crates/actix-ws)
2024-07-20 08:24:20 +02:00
[![Documentation](https://docs.rs/actix-ws/badge.svg?version=0.3.0)](https://docs.rs/actix-ws/0.3.0)
2024-07-20 08:23:21 +02:00
![Version](https://img.shields.io/badge/rustc-1.75+-ab6000.svg)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-ws.svg)
<br />
2024-07-20 08:24:20 +02:00
[![Dependency Status](https://deps.rs/crate/actix-ws/0.3.0/status.svg)](https://deps.rs/crate/actix-ws/0.3.0)
2024-07-20 08:23:21 +02:00
[![Download](https://img.shields.io/crates/d/actix-ws.svg)](https://crates.io/crates/actix-ws)
[![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x)
2023-11-03 23:49:18 +01:00
2024-01-06 22:08:09 +01:00
<!-- prettier-ignore-end -->
2024-07-20 08:23:21 +02:00
## Example
2023-11-03 23:49:18 +01:00
```rust
2024-06-20 02:55:14 +02:00
use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Responder};
2023-11-03 23:49:18 +01:00
use actix_ws::Message;
2024-06-20 02:55:14 +02:00
async fn ws(req: HttpRequest, body: web::Payload) -> actix_web::Result<impl Responder> {
2023-11-03 23:49:18 +01:00
let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;
2024-06-20 02:55:14 +02:00
actix_web::rt::spawn(async move {
2023-11-03 23:49:18 +01:00
while let Some(Ok(msg)) = msg_stream.next().await {
match msg {
Message::Ping(bytes) => {
if session.pong(&bytes).await.is_err() {
return;
}
}
2024-06-20 02:55:14 +02:00
Message::Text(msg) => println!("Got text: {msg}"),
2023-11-03 23:49:18 +01:00
_ => break,
}
}
let _ = session.close(None).await;
});
Ok(response)
}
#[actix_web::main]
2024-06-20 02:55:14 +02:00
async fn main() -> std::io::Result<()> {
2023-11-03 23:49:18 +01:00
HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.route("/ws", web::get().to(ws))
})
.bind("127.0.0.1:8080")?
.run()
.await?;
Ok(())
}
```
2024-07-20 08:23:21 +02:00
## Resources
- [API Documentation](https://docs.rs/actix-ws)
- [Example Chat Project](https://github.com/actix/examples/tree/master/websockets/chat-actorless)
- Minimum Supported Rust Version (MSRV): 1.75
2023-11-03 23:49:18 +01:00
## License
This project is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.