1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

remove select macro from echo example

This commit is contained in:
Rob Ede
2022-07-11 20:19:20 +01:00
parent a4a060994d
commit fd17252725
9 changed files with 31 additions and 23 deletions

View File

@ -11,6 +11,6 @@ awc = "3"
env_logger = "0.9"
futures-util = { version = "0.3.7", default-features = false, features = ["std", "sink"] }
futures-lite = "1.3"
log = "0.4"
tokio = { version = "1.13.1", features = ["full"] }
tokio-stream = "0.1.8"

View File

@ -12,9 +12,9 @@ cargo run
# starting HTTP server at http://localhost:8080
```
### Web Client
### Browser Client
Go to <http://localhost:8080/> in a browser.
Go to <http://localhost:8080> in a browser.
### CLI Client

View File

@ -2,8 +2,8 @@ use std::time::{Duration, Instant};
use actix_web::rt;
use actix_ws::Message;
use futures_util::stream::StreamExt as _;
use tokio::select;
use futures_lite::future;
use futures_util::{future::Either, stream::StreamExt as _, FutureExt as _};
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
@ -20,12 +20,16 @@ pub async fn echo_heartbeat_ws(
log::info!("connected");
let mut last_heartbeat = Instant::now();
let mut interval = rt::time::interval(HEARTBEAT_INTERVAL);
loop {
select! {
Some(Ok(msg)) = msg_stream.next() => {
match future::or(
msg_stream.next().map(Either::Left),
interval.tick().map(Either::Right),
)
.await
{
Either::Left(Some(Ok(msg))) => {
log::debug!("msg: {msg:?}");
match msg {
@ -58,10 +62,14 @@ pub async fn echo_heartbeat_ws(
}
}
_ = interval.tick() => {
Either::Left(_) => {}
Either::Right(_) => {
// if no heartbeat ping/pong received recently, close the connection
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
log::info!("client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting");
log::info!(
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
);
let _ = session.close(None).await;
break;
}