forked from gorb/backend
feat: add basic WebSocket server with echo handler
This commit is contained in:
parent
b499ff1cf8
commit
79cfa25855
3 changed files with 91 additions and 37 deletions
40
src/wss.rs
Normal file
40
src/wss.rs
Normal file
|
@ -0,0 +1,40 @@
|
|||
use actix_web::{rt, web, Error, HttpRequest, HttpResponse};
|
||||
use actix_ws::AggregatedMessage;
|
||||
use futures_util::StreamExt as _;
|
||||
|
||||
pub async fn echo(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
|
||||
let (res, mut session, stream) = actix_ws::handle(&req, stream)?;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
Ok(AggregatedMessage::Ping(msg)) => {
|
||||
// respond to PING frame with PONG frame
|
||||
session.pong(&msg).await.unwrap();
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// respond immediately with response connected to WS session
|
||||
Ok(res)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue