123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- 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<int, Connection> connections = new ConcurrentDictionary<int, Connection>();
- private ConcurrentDictionary<string, List<Connection>> channels = new ConcurrentDictionary<string, List<Connection>>();
- 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<Connection> GetActive()
- {
- var activeConnections = new List<Connection>();
- 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<Connection>());
- var foundMatch = connectionsInChannel.Find(x => x.Equals(connection));
- if(foundMatch == null) {
- connectionsInChannel.Add(connection);
- }
- }
- }
- }
|