-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocketRepository.cs
52 lines (43 loc) · 1.57 KB
/
SocketRepository.cs
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
50
51
52
using System.Net.WebSockets;
namespace TNRD.Zeepkist.GTR.Stream;
public class SocketRepository
{
public record SocketData(WebSocket WebSocket, TaskCompletionSource<object> Tcs);
private readonly List<SocketData> webSockets = new List<SocketData>();
public void Add(WebSocket webSocket, TaskCompletionSource<object> tcs)
{
SocketData socketData = new SocketData(webSocket, tcs);
webSockets.Add(socketData);
WaitForSocketClose(socketData);
}
private async void WaitForSocketClose(SocketData socketData)
{
try
{
byte[] buffer = new byte[1024 * 4];
WebSocketReceiveResult receiveResult = await socketData.WebSocket.ReceiveAsync(
new ArraySegment<byte>(buffer),
CancellationToken.None);
while (!receiveResult.CloseStatus.HasValue)
{
receiveResult = await socketData.WebSocket.ReceiveAsync(
new ArraySegment<byte>(buffer),
CancellationToken.None);
}
await socketData.WebSocket.CloseAsync(
receiveResult.CloseStatus.Value,
receiveResult.CloseStatusDescription,
CancellationToken.None);
}
catch (Exception e)
{
socketData.Tcs.SetException(e);
return;
}
socketData.Tcs.SetCanceled();
}
public IReadOnlyList<SocketData> GetSockets()
{
return new List<SocketData>(webSockets.Where(x => !x.Tcs.Task.IsCanceled && !x.Tcs.Task.IsFaulted));
}
}