1
0
mirror of https://github.com/actix/examples synced 2024-12-01 01:24:35 +01:00
examples/websockets/echo-actorless/src/handler.rs

157 lines
4.9 KiB
Rust
Raw Normal View History

2022-07-11 02:44:46 +02:00
use std::time::{Duration, Instant};
use actix_ws::Message;
2022-07-12 02:08:15 +02:00
use futures_util::{
future::{self, Either},
StreamExt as _,
};
use tokio::{pin, time::interval};
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
/// How often heartbeat pings are sent.
///
/// Should be half (or less) of the acceptable client timeout.
2022-07-11 02:44:46 +02:00
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
2022-07-12 02:08:15 +02:00
/// How long before lack of client response causes a timeout.
2022-07-11 02:44:46 +02:00
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// Echo text & binary messages received from the client, respond to ping messages, and monitor
/// connection health to detect network issues and free up resources.
pub async fn echo_heartbeat_ws(
mut session: actix_ws::Session,
mut msg_stream: actix_ws::MessageStream,
) {
log::info!("connected");
let mut last_heartbeat = Instant::now();
2022-07-12 02:08:15 +02:00
let mut interval = interval(HEARTBEAT_INTERVAL);
let reason = loop {
// create "next client timeout check" future
let tick = interval.tick();
// required for select()
pin!(tick);
// waits for either `msg_stream` to receive a message from the client or the heartbeat
// interval timer to tick, yielding the value of whichever one is ready first
match future::select(msg_stream.next(), tick).await {
// received message from WebSocket client
Either::Left((Some(Ok(msg)), _)) => {
2022-07-11 02:44:46 +02:00
log::debug!("msg: {msg:?}");
match msg {
Message::Text(text) => {
session.text(text).await.unwrap();
}
Message::Binary(bin) => {
session.binary(bin).await.unwrap();
}
Message::Close(reason) => {
2022-07-12 02:08:15 +02:00
break reason;
}
Message::Ping(bytes) => {
last_heartbeat = Instant::now();
let _ = session.pong(&bytes).await;
2022-07-11 02:44:46 +02:00
}
2022-07-12 02:08:15 +02:00
Message::Pong(_) => {
last_heartbeat = Instant::now();
2022-07-11 02:44:46 +02:00
}
2022-07-12 02:08:15 +02:00
Message::Continuation(_) => {
log::warn!("no support for continuation frames");
}
// no-op; ignore
Message::Nop => {}
};
}
// client WebSocket stream error
Either::Left((Some(Err(err)), _)) => {
log::error!("{}", err);
2022-07-11 02:44:46 +02:00
}
2022-07-12 02:08:15 +02:00
// client WebSocket stream ended
Either::Left((None, _)) => break None,
2022-07-11 21:19:20 +02:00
2022-07-12 02:08:15 +02:00
// heartbeat interval ticked
Either::Right((_inst, _)) => {
2022-07-11 02:44:46 +02:00
// if no heartbeat ping/pong received recently, close the connection
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
2022-07-11 21:19:20 +02:00
log::info!(
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
);
2022-07-12 02:08:15 +02:00
break None;
2022-07-11 02:44:46 +02:00
}
// send heartbeat ping
let _ = session.ping(b"").await;
}
2022-07-12 02:08:15 +02:00
}
};
// attempt to close connection gracefully
let _ = session.close(reason).await;
log::info!("disconnected");
2022-07-11 02:44:46 +02:00
}
/// Echo text & binary messages received from the client and respond to ping messages.
///
/// This example is just for demonstration of simplicity. In reality, you likely want to include
/// some handling of heartbeats for connection health tracking to free up server resources when
/// connections die or network issues arise.
2022-07-12 02:08:15 +02:00
///
/// See [`echo_heartbeat_ws`] for a more realistic implementation.
2022-07-11 02:44:46 +02:00
pub async fn echo_ws(mut session: actix_ws::Session, mut msg_stream: actix_ws::MessageStream) {
log::info!("connected");
2022-07-12 02:08:15 +02:00
let close_reason = loop {
match msg_stream.next().await {
Some(Ok(msg)) => {
log::debug!("msg: {msg:?}");
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
match msg {
Message::Text(text) => {
session.text(text).await.unwrap();
}
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
Message::Binary(bin) => {
session.binary(bin).await.unwrap();
}
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
Message::Close(reason) => {
break reason;
}
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
Message::Ping(bytes) => {
let _ = session.pong(&bytes).await;
}
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
Message::Pong(_) => {}
Message::Continuation(_) => {
log::warn!("no support for continuation frames");
}
2022-07-11 02:44:46 +02:00
2022-07-12 02:08:15 +02:00
// no-op; ignore
Message::Nop => {}
};
2022-07-11 02:44:46 +02:00
}
2022-07-12 02:08:15 +02:00
// error or end of stream
_ => break None,
2022-07-11 02:44:46 +02:00
}
2022-07-12 02:08:15 +02:00
};
// attempt to close connection gracefully
let _ = session.close(close_reason).await;
log::info!("disconnected");
2022-07-11 02:44:46 +02:00
}