MCPcopy Create free account
hub / github.com/actix/examples / echo_ws

Function echo_ws

websockets/echo-actorless/src/handler.rs:113–158  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

111 match msg {
112 AggregatedMessage::Text(text) => {
113 session.text(text).await.unwrap();
114 }
115
116 AggregatedMessage::Binary(bin) => {
117 session.binary(bin).await.unwrap();
118 }
119
120 AggregatedMessage::Close(reason) => {
121 break reason;
122 }
123
124 AggregatedMessage::Ping(bytes) => {
125 let _ = session.pong(&bytes).await;
126 }
127
128 AggregatedMessage::Pong(_) => {}
129 };
130 }
131
132 // error or end of stream
133 _ => break None,
134 }
135 };
136
137 // attempt to close connection gracefully
138 let _ = session.close(close_reason).await;
139
140 log::info!("Disconnected");
141}
142
143/// Broadcast text & binary messages received from a client, respond to ping messages, and monitor
144/// connection health to detect network issues and free up resources.
145pub async fn broadcast_ws(
146 mut session: Session,
147 mut msg_stream: MessageStream,
148 mut rx: broadcast::Receiver<web::Bytes>,
149) {
150 log::info!("Connected");
151
152 let mut last_heartbeat = Instant::now();
153 let mut interval = interval(HEARTBEAT_INTERVAL);
154
155 let reason = loop {
156 // waits for either `msg_stream` to receive a message from the client, the broadcast channel
157 // to send a message, or the heartbeat interval timer to tick, yielding the value of
158 // whichever one is ready first
159 select! {
160 broadcast_msg = rx.recv() => {
161 let msg = match broadcast_msg {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected