Echo text & binary messages received from the client, respond to ping messages, and monitor connection health to detect network issues and free up resources.
(
mut session: actix_ws::Session,
mut msg_stream: actix_ws::MessageStream,
)
| 19 | /// Echo text & binary messages received from the client, respond to ping messages, and monitor |
| 20 | /// connection health to detect network issues and free up resources. |
| 21 | pub async fn echo_heartbeat_ws( |
| 22 | mut session: actix_ws::Session, |
| 23 | mut msg_stream: actix_ws::MessageStream, |
| 24 | ) { |
| 25 | log::info!("connected"); |
| 26 | |
| 27 | let mut last_heartbeat = Instant::now(); |
| 28 | let mut interval = interval(HEARTBEAT_INTERVAL); |
| 29 | |
| 30 | let reason = loop { |
| 31 | // create "next client timeout check" future |
| 32 | let tick = interval.tick(); |
| 33 | // required for select() |
| 34 | pin!(tick); |
| 35 | |
| 36 | // waits for either `msg_stream` to receive a message from the client or the heartbeat |
| 37 | // interval timer to tick, yielding the value of whichever one is ready first |
| 38 | match future::select(msg_stream.next(), tick).await { |
| 39 | // received message from WebSocket client |
| 40 | Either::Left((Some(Ok(msg)), _)) => { |
| 41 | log::debug!("msg: {msg:?}"); |
| 42 | |
| 43 | match msg { |
| 44 | Message::Text(text) => { |
| 45 | session.text(text).await.unwrap(); |
| 46 | } |
| 47 | |
| 48 | Message::Binary(bin) => { |
| 49 | session.binary(bin).await.unwrap(); |
| 50 | } |
| 51 | |
| 52 | Message::Close(reason) => { |
| 53 | break reason; |
| 54 | } |
| 55 | |
| 56 | Message::Ping(bytes) => { |
| 57 | last_heartbeat = Instant::now(); |
| 58 | let _ = session.pong(&bytes).await; |
| 59 | } |
| 60 | |
| 61 | Message::Pong(_) => { |
| 62 | last_heartbeat = Instant::now(); |
| 63 | } |
| 64 | |
| 65 | Message::Continuation(_) => { |
| 66 | log::warn!("no support for continuation frames"); |
| 67 | } |
| 68 | |
| 69 | // no-op; ignore |
| 70 | Message::Nop => {} |
| 71 | }; |
| 72 | } |
| 73 | |
| 74 | // client WebSocket stream error |
| 75 | Either::Left((Some(Err(err)), _)) => { |
| 76 | log::error!("{}", err); |
| 77 | break None; |
| 78 | } |