expression
WebSocket: bound the outgoing message queue
A slow client can cause outgoing messages to accumulate. Bound its queue and define a policy for a full queue, such as rejecting nonessential updates or disconnecting slow clients. This local queue model explicitly rejects a third message instead of accumulating memory; it does not send anything to a socket. Standalone synthetic example. Expected stdout (not executed): one: true two: true three: false read: one read: two Common mistake: Using an unlimited queue without a slow-client policy or silently dropping critical messages.
Formal Syntax & Structure
rust syntaxrust
tokio::sync::mpsc::channel::<Message>(capacity)Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { let (tx, mut rx) = tokio::sync::mpsc::channel::<Message>(2); for text in ["one", "two", "three"] { println!("{text}: {}", tx.try_send(Message::Text(text.into())).is_ok()); } drop(tx); while let Some(Message::Text(text)) = rx.recv().await { println!("read: {text}"); }}