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. See [`echo_heartbeat_ws`] for a more realistic implementation.
(mut session: actix_ws::Session, mut msg_stream: actix_ws::MessageStream)
| 111 | /// |
| 112 | /// See [`echo_heartbeat_ws`] for a more realistic implementation. |
| 113 | pub async fn echo_ws(mut session: actix_ws::Session, mut msg_stream: actix_ws::MessageStream) { |
| 114 | log::info!("connected"); |
| 115 | |
| 116 | let close_reason = loop { |
| 117 | match msg_stream.next().await { |
| 118 | Some(Ok(msg)) => { |
| 119 | log::debug!("msg: {msg:?}"); |
| 120 | |
| 121 | match msg { |
| 122 | Message::Text(text) => { |
| 123 | session.text(text).await.unwrap(); |
| 124 | } |
| 125 | |
| 126 | Message::Binary(bin) => { |
| 127 | session.binary(bin).await.unwrap(); |
| 128 | } |
| 129 | |
| 130 | Message::Close(reason) => { |
| 131 | break reason; |
| 132 | } |
| 133 | |
| 134 | Message::Ping(bytes) => { |
| 135 | let _ = session.pong(&bytes).await; |
| 136 | } |
| 137 | |
| 138 | Message::Pong(_) => {} |
| 139 | |
| 140 | Message::Continuation(_) => { |
| 141 | log::warn!("no support for continuation frames"); |
| 142 | } |
| 143 | |
| 144 | // no-op; ignore |
| 145 | Message::Nop => {} |
| 146 | }; |
| 147 | } |
| 148 | |
| 149 | // error or end of stream |
| 150 | _ => break None, |
| 151 | } |
| 152 | }; |
| 153 | |
| 154 | // attempt to close connection gracefully |
| 155 | let _ = session.close(close_reason).await; |
| 156 | |
| 157 | log::info!("disconnected"); |
| 158 | } |
| 159 | |
| 160 | /// Broadcast text & binary messages received from a client, respond to ping messages, and monitor |
| 161 | /// connection health to detect network issues and free up resources. |
nothing calls this directly
no outgoing calls
no test coverage detected