Echo text & binary messages received from the client, respond to ping messages, and monitor connection health to detect network issues and free up resources.
(
chat_server: ChatServerHandle,
mut session: actix_ws::Session,
msg_stream: actix_ws::MessageStream,
)
| 15 | /// Echo text & binary messages received from the client, respond to ping messages, and monitor |
| 16 | /// connection health to detect network issues and free up resources. |
| 17 | pub async fn chat_ws( |
| 18 | chat_server: ChatServerHandle, |
| 19 | mut session: Session, |
| 20 | mut msg_stream: AggregatedMessageStream, |
| 21 | ) { |
| 22 | log::info!("Connected"); |
| 23 | |
| 24 | let mut name: Option<String> = None; |
| 25 | let mut last_heartbeat = Instant::now(); |
| 26 | let mut interval = interval(HEARTBEAT_INTERVAL); |
| 27 | |
| 28 | let (conn_tx, mut conn_rx) = mpsc::unbounded_channel(); |
| 29 | |
| 30 | // unwrap: chat server is not dropped before the HTTP server |
| 31 | let conn_id = chat_server.connect(conn_tx).await; |
| 32 | |
| 33 | let close_reason = loop { |
| 34 | tokio::select! { |
| 35 | Some(Ok(msg)) = msg_stream.next() => { |
| 36 | log::debug!("Msg: {msg:?}"); |
| 37 | |
| 38 | match msg { |
| 39 | AggregatedMessage::Ping(bytes) => { |
| 40 | last_heartbeat = Instant::now(); |
| 41 | session.pong(&bytes).await.unwrap(); |
| 42 | } |
| 43 | |
| 44 | AggregatedMessage::Pong(_) => { |
| 45 | last_heartbeat = Instant::now(); |
| 46 | } |
| 47 | |
| 48 | AggregatedMessage::Text(text) => { |
| 49 | process_text_msg(&chat_server, &mut session, &text, conn_id, &mut name) |
| 50 | .await; |
| 51 | } |
| 52 | |
| 53 | AggregatedMessage::Binary(_bin) => { |
| 54 | log::warn!("Unexpected binary message"); |
| 55 | } |
| 56 | |
| 57 | AggregatedMessage::Close(reason) => break reason, |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | Some(chat_msg) = conn_rx.recv() => { |
| 62 | session.text(chat_msg).await.unwrap(); |
| 63 | } |
| 64 | |
| 65 | _ = interval.tick() => { |
| 66 | if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT { |
| 67 | break None; |
| 68 | } |
| 69 | let _ = session.ping(b"").await; |
| 70 | } |
| 71 | |
| 72 | else => { |
| 73 | break None; |
| 74 | } |
nothing calls this directly
no test coverage detected