handle_websocket

Function handle_websocket 

Source
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

  1. Connection is added to the manager
  2. on_connect callback is invoked
  3. Read and write tasks run concurrently
  4. When either task completes, both are terminated
  5. Connection is removed from the manager
  6. on_disconnect callback is invoked

§Arguments

  • stream - The WebSocket stream
  • conn_id - Unique identifier for this connection
  • peer_addr - Socket address of the connected client
  • manager - Shared connection manager
  • on_message - Callback invoked when a message is received
  • on_connect - Callback invoked when the connection is established
  • on_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;