-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSimpleWebsocketCollection.cs
More file actions
49 lines (38 loc) · 1.24 KB
/
SimpleWebsocketCollection.cs
File metadata and controls
49 lines (38 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Collections.Concurrent;
namespace OpenShock.Common.Websocket;
public sealed class SimpleWebsocketCollection<T, TR> where T : class, IWebsocketController<TR>
{
private readonly ConcurrentDictionary<Guid, List<T>> _websockets = new();
public void RegisterConnection(T controller)
{
var list = _websockets.GetOrAdd(controller.Id, [controller]);
lock (list)
{
if (!list.Contains(controller)) list.Add(controller);
}
}
public bool UnregisterConnection(T controller)
{
var key = controller.Id;
if (!_websockets.TryGetValue(key, out var list)) return false;
lock (list)
{
if (!list.Remove(controller)) return false;
if (list.Count == 0)
{
_websockets.TryRemove(key, out _);
}
}
return true;
}
public bool IsConnected(Guid id) => _websockets.ContainsKey(id);
public T[] GetConnections(Guid id)
{
if (!_websockets.TryGetValue(id, out var list)) return [];
lock (list)
{
return list.ToArray();
}
}
public uint Count => (uint)_websockets.Sum(kvp => { lock (kvp.Value) { return kvp.Value.Count; } });
}