1
0
mirror of https://github.com/actix/actix-website synced 2025-02-13 00:25:35 +01:00

57 lines
1.7 KiB
Rust
Raw Normal View History

2019-06-17 18:07:57 -04:00
// <websockets>
use actix_web::{rt, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_ws::AggregatedMessage;
use futures_util::StreamExt as _;
2019-06-17 18:07:57 -04:00
async fn echo(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
let (res, mut session, stream) = actix_ws::handle(&req, stream)?;
2019-06-17 18:07:57 -04:00
let mut stream = stream
.aggregate_continuations()
// aggregate continuation frames up to 1MiB
.max_continuation_size(2_usize.pow(20));
// start task but don't wait for it
rt::spawn(async move {
// receive messages from websocket
while let Some(msg) = stream.next().await {
match msg {
Ok(AggregatedMessage::Text(text)) => {
// echo text message
session.text(text).await.unwrap();
}
Ok(AggregatedMessage::Binary(bin)) => {
// echo binary message
session.binary(bin).await.unwrap();
}
2019-06-17 18:07:57 -04:00
Ok(AggregatedMessage::Ping(msg)) => {
// respond to PING frame with PONG frame
session.pong(&msg).await.unwrap();
}
_ => {}
}
2019-06-26 12:55:12 -04:00
}
});
2019-06-17 18:07:57 -04:00
// respond immediately with response connected to WS session
Ok(res)
2019-06-26 12:55:12 -04:00
}
2020-09-12 16:21:54 +01:00
#[actix_web::main]
2019-12-29 04:16:54 +09:00
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/echo", web::get().to(echo)))
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2019-06-26 12:55:12 -04:00
.run()
2019-12-29 04:16:54 +09:00
.await
2019-06-26 12:55:12 -04:00
}
2019-06-17 18:07:57 -04:00
// </websockets>
2019-06-26 12:55:12 -04:00
// testing requires specific headers:
// Upgrade: websocket
// Connection: Upgrade
// Sec-WebSocket-Key: SOME_KEY
// Sec-WebSocket-Version: 13