pub async fn handle_websocket(
stream: WebSocketStream<TcpStream>,
conn_id: ConnectionId,
peer_addr: SocketAddr,
manager: Arc<ConnectionManager>,
on_message: Arc<dyn Fn(ConnectionId, Message) + Send + Sync>,
on_connect: Arc<dyn Fn(ConnectionId) + Send + Sync>,
on_disconnect: Arc<dyn Fn(ConnectionId) + Send + Sync>,
)Expand description
Handles the lifecycle of a WebSocket connection.
This function manages the entire lifecycle of a WebSocket connection from establishment to termination. It spawns two concurrent tasks:
- A read task that receives messages from the client
- A write task that sends messages to the client
§Architecture
The function uses a split WebSocket stream and an unbounded channel to decouple reading and writing operations. This ensures that slow clients don’t block message processing and allows for efficient broadcasting.
§Lifecycle Events
- Connection is added to the manager
on_connectcallback is invoked- Read and write tasks run concurrently
- When either task completes, both are terminated
- Connection is removed from the manager
on_disconnectcallback is invoked
§Arguments
stream- The WebSocket streamconn_id- Unique identifier for this connectionpeer_addr- Socket address of the connected clientmanager- Shared connection manageron_message- Callback invoked when a message is receivedon_connect- Callback invoked when the connection is establishedon_disconnect- Callback invoked when the connection is closed
§Examples
This function is typically called by the router and not directly by users. However, for custom implementations:
use wsforge::prelude::*;
use std::sync::Arc;
use tokio_tungstenite::accept_async;
let ws_stream = accept_async(stream).await?;
let conn_id = "conn_0".to_string();
let manager = Arc::new(ConnectionManager::new());
let on_message = Arc::new(|id: ConnectionId, msg: Message| {
println!("Received from {}: {:?}", id, msg);
});
let on_connect = Arc::new(|id: ConnectionId| {
println!("Connected: {}", id);
});
let on_disconnect = Arc::new(|id: ConnectionId| {
println!("Disconnected: {}", id);
});
handle_websocket(
ws_stream,
conn_id,
peer_addr,
manager,
on_message,
on_connect,
on_disconnect,
).await;