-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSocketManager.cs
143 lines (115 loc) · 4.9 KB
/
WebSocketManager.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dashboard;
using Microsoft.AspNetCore.Builder;
namespace Journal
{
public class WebSocketManager : IWebsocketManager
{
private List<WebSocket> sockets = new List<WebSocket>();
public void SetupWebsockets(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
if (context.Request.Path == "/events")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
lock (sockets) sockets.Add(webSocket);
var msg = await ReceiveStringAsync(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
}
private static async Task<string> ReceiveStringAsync(WebSocket socket, CancellationToken ct = default(CancellationToken))
{
var buffer = new ArraySegment<byte>(new byte[8192]);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
ct.ThrowIfCancellationRequested();
result = await socket.ReceiveAsync(buffer, ct);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType != WebSocketMessageType.Text)
{
return null;
}
// Encoding UTF8: https://tools.ietf.org/html/rfc6455#section-5.6
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
}
}
}
// private async Task HandleWebsocket(HttpContext context, WebSocket webSocket)
// {
// var buffer = new byte[1024 * 4];
// WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// while (!result.CloseStatus.HasValue)
// {
// await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
// result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// }
// await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
// }
// private async Task<(WebSocketReceiveResult, IEnumerable<byte>)> ReceiveFullMessage(
//WebSocket socket, CancellationToken cancelToken)
// {
// WebSocketReceiveResult response;
// var message = new List<byte>();
// var buffer = new byte[4096];
// do
// {
// response = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
// message.AddRange(new ArraySegment<byte>(buffer, 0, response.Count));
// } while (!response.EndOfMessage);
// return (response, message);
// }
public int OpenConnections => sockets.Where(s => s.State == WebSocketState.Open).Count();
public void Send(string message)
{
WebSocket[] socks;
lock (sockets)
socks = sockets.ToArray();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
List<Task> tasks = new List<Task>();
foreach (var s in socks)
{
if (s.State == WebSocketState.Open)
tasks.Add(s.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None));
}
try
{
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException ex)
{
foreach (var iex in ex.InnerExceptions)
{
Console.Error.WriteLine("Error: " + iex.GetType().FullName + " - " + iex.Message);
}
}
lock (sockets) sockets.RemoveAll(s => s.State != WebSocketState.Open && s.State != WebSocketState.Connecting);
}
}
}