ConnectionManager

Struct ConnectionManager 

Source
pub struct ConnectionManager { /* private fields */ }
Expand description

Manages a collection of active WebSocket connections.

ConnectionManager provides thread-safe operations for managing connections, including adding, removing, and broadcasting messages. It uses DashMap internally for lock-free concurrent access.

§Thread Safety

All operations are thread-safe and can be called from multiple threads concurrently without additional synchronization.

§Examples

§Basic Usage

use wsforge::prelude::*;
use std::sync::Arc;

let manager = Arc::new(ConnectionManager::new());

// Get connection count
let count = manager.count();
println!("Active connections: {}", count);

// Get all connection IDs
let ids = manager.all_ids();
for id in ids {
    println!("Connection: {}", id);
}

§Broadcasting

use wsforge::prelude::*;
use std::sync::Arc;

// Broadcast system announcement
manager.broadcast(Message::text("Server maintenance in 5 minutes"));

// Notify everyone except the sender
let sender_id = "conn_42";
manager.broadcast_except(&sender_id.to_string(),
    Message::text("New user joined the chat"));

Implementations§

Source§

impl ConnectionManager

Source

pub fn new() -> Self

Creates a new empty ConnectionManager.

§Examples
use wsforge::prelude::*;
use std::sync::Arc;

let manager = Arc::new(ConnectionManager::new());
assert_eq!(manager.count(), 0);
Source

pub fn add(&self, conn: Connection) -> usize

Adds a connection to the manager.

Returns the total number of connections after adding.

§Examples
use wsforge::prelude::*;
use tokio::sync::mpsc;
use std::net::SocketAddr;

let manager = ConnectionManager::new();
let (tx, rx) = mpsc::unbounded_channel();
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let conn = Connection::new("conn_0".to_string(), addr, tx);

let count = manager.add(conn);
assert_eq!(count, 1);
Source

pub fn remove(&self, id: &ConnectionId) -> Option<Connection>

Removes a connection from the manager.

Returns the removed connection if it existed, or None if not found.

§Examples
use wsforge::prelude::*;

let conn_id = "conn_42".to_string();
if let Some(conn) = manager.remove(&conn_id) {
    println!("Removed connection: {}", conn.id());
}
Source

pub fn get(&self, id: &ConnectionId) -> Option<Connection>

Retrieves a connection by its ID.

Returns a clone of the connection if found, or None if not found.

§Performance

This operation is O(1) and does not block other concurrent operations.

§Examples
use wsforge::prelude::*;

let conn_id = "conn_0".to_string();
if let Some(conn) = manager.get(&conn_id) {
    conn.send_text("Hello!")?;
}
Source

pub fn broadcast(&self, message: Message)

Broadcasts a message to all active connections.

This method iterates through all connections and sends the message to each one. Failed sends are logged but do not stop the broadcast.

§Performance

Broadcasts are performed synchronously but send operations are async, so messages are queued immediately and sent in the background.

§Examples
use wsforge::prelude::*;

manager.broadcast(Message::text("Server announcement!"));
Source

pub fn broadcast_except(&self, except_id: &ConnectionId, message: Message)

Broadcasts a message to all connections except one.

This is useful for notifying all users about an action taken by one user, without sending the notification back to the actor.

§Examples
use wsforge::prelude::*;

let sender_id = "conn_42".to_string();
manager.broadcast_except(&sender_id,
    Message::text("User 42 sent a message"));
Source

pub fn broadcast_to(&self, ids: &[ConnectionId], message: Message)

Broadcasts a message to specific connections.

Only connections whose IDs are in the provided list will receive the message. Non-existent connection IDs are silently ignored.

§Examples
use wsforge::prelude::*;

let vip_users = vec![
    "conn_1".to_string(),
    "conn_5".to_string(),
    "conn_10".to_string(),
];
manager.broadcast_to(&vip_users, Message::text("VIP announcement"));
Source

pub fn count(&self) -> usize

Returns the number of active connections.

§Examples
use wsforge::prelude::*;

let count = manager.count();
println!("Active connections: {}", count);
Source

pub fn all_ids(&self) -> Vec<ConnectionId>

Returns a list of all connection IDs.

The order of IDs is not guaranteed.

§Examples
use wsforge::prelude::*;

for id in manager.all_ids() {
    println!("Connection ID: {}", id);
}
Source

pub fn all_connections(&self) -> Vec<Connection>

Returns clones of all active connections.

This is useful for batch operations on all connections.

§Performance

Since connections are lightweight (they contain Arc internally), cloning is cheap.

§Examples
use wsforge::prelude::*;

for conn in manager.all_connections() {
    conn.send_text("Shutdown in 1 minute")?;
}

Trait Implementations§

Source§

impl Default for ConnectionManager

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more