using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.WebSockets; namespace BubbleSocketCore.Websocket { public class ConnectionManager { private static ConnectionManager instance; public static ConnectionManager GetInstance() { if (ConnectionManager.instance == null) { ConnectionManager.instance = new ConnectionManager(); } return ConnectionManager.instance; } private ConcurrentDictionary connections = new ConcurrentDictionary(); private ConcurrentDictionary> channels = new ConcurrentDictionary>(); public ConnectionManager() { } public void Add(WebSocket websocket) { connections.TryAdd(websocket.GetHashCode(), new Connection(websocket)); } public Connection Remove(int hashCode) { Connection removedConnection; connections.TryRemove(hashCode, out removedConnection); return removedConnection; } public List GetActive() { var activeConnections = new List(); foreach (Connection conn in connections.Values) { if (conn.State == WebSocketState.Open) { activeConnections.Add(conn); } } return activeConnections; } public Connection GetConnection(int hashCode) { Connection connection; connections.TryGetValue(hashCode, out connection); return connection; } public void JoinChannel(string channel, Connection connection) { var connectionsInChannel = channels.GetOrAdd(channel, new List()); var foundMatch = connectionsInChannel.Find(x => x.Equals(connection)); if(foundMatch == null) { connectionsInChannel.Add(connection); } } } }