ConnectionManager.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Net.WebSockets;
  5. namespace BubbleSocketCore.Websocket
  6. {
  7. public class ConnectionManager
  8. {
  9. private static ConnectionManager instance;
  10. public static ConnectionManager GetInstance()
  11. {
  12. if (ConnectionManager.instance == null)
  13. {
  14. ConnectionManager.instance = new ConnectionManager();
  15. }
  16. return ConnectionManager.instance;
  17. }
  18. private ConcurrentDictionary<int, Connection> connections = new ConcurrentDictionary<int, Connection>();
  19. private ConcurrentDictionary<string, List<Connection>> channels = new ConcurrentDictionary<string, List<Connection>>();
  20. public ConnectionManager()
  21. {
  22. }
  23. public void Add(WebSocket websocket)
  24. {
  25. connections.TryAdd(websocket.GetHashCode(), new Connection(websocket));
  26. }
  27. public Connection Remove(int hashCode)
  28. {
  29. Connection removedConnection;
  30. connections.TryRemove(hashCode, out removedConnection);
  31. return removedConnection;
  32. }
  33. public List<Connection> GetActive()
  34. {
  35. var activeConnections = new List<Connection>();
  36. foreach (Connection conn in connections.Values)
  37. {
  38. if (conn.State == WebSocketState.Open)
  39. {
  40. activeConnections.Add(conn);
  41. }
  42. }
  43. return activeConnections;
  44. }
  45. public Connection GetConnection(int hashCode)
  46. {
  47. Connection connection;
  48. connections.TryGetValue(hashCode, out connection);
  49. return connection;
  50. }
  51. public void JoinChannel(string channel, Connection connection) {
  52. var connectionsInChannel = channels.GetOrAdd(channel, new List<Connection>());
  53. var foundMatch = connectionsInChannel.Find(x => x.Equals(connection));
  54. if(foundMatch == null) {
  55. connectionsInChannel.Add(connection);
  56. }
  57. }
  58. }
  59. }