forked from MV10/WebSocketExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketMiddleware.cs
More file actions
218 lines (193 loc) · 9.44 KB
/
Copy pathWebSocketMiddleware.cs
File metadata and controls
218 lines (193 loc) · 9.44 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
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ChannelWSServer
{
public class WebSocketMiddleware : IMiddleware
{
private static int SocketCounter = 0;
// The key is a socket id
private static ConcurrentDictionary<int, ConnectedClient> Clients = new ConcurrentDictionary<int, ConnectedClient>();
public static CancellationTokenSource SocketLoopTokenSource = new CancellationTokenSource();
private static bool ServerIsRunning = true;
private static CancellationTokenRegistration AppShutdownHandler;
// use dependency injection to grab a reference to the hosting container's lifetime cancellation tokens
public WebSocketMiddleware(IHostApplicationLifetime hostLifetime)
{
// gracefully close all websockets during shutdown (only register on first instantiation)
if(AppShutdownHandler.Token.Equals(CancellationToken.None))
AppShutdownHandler = hostLifetime.ApplicationStopping.Register(ApplicationShutdownHandler);
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
if(ServerIsRunning)
{
if (context.WebSockets.IsWebSocketRequest)
{
int socketId = Interlocked.Increment(ref SocketCounter);
var socket = await context.WebSockets.AcceptWebSocketAsync();
var completion = new TaskCompletionSource<object>();
var client = new ConnectedClient(socketId, socket, completion);
Clients.TryAdd(socketId, client);
Console.WriteLine($"Socket {socketId}: New connection.");
// TaskCompletionSource<> is used to keep the middleware pipeline alive;
// SocketProcessingLoop calls TrySetResult upon socket termination
_ = Task.Run(() => SocketProcessingLoopAsync(client).ConfigureAwait(false));
await completion.Task;
}
else
{
if (context.Request.Headers["Accept"][0].Contains("text/html"))
{
Console.WriteLine("Sending HTML to client.");
await context.Response.WriteAsync(SimpleHtmlClient.HTML);
}
else
{
// ignore other requests (such as favicon)
// potentially other middleware will handle it (see finally block)
}
}
}
else
{
// ServerIsRunning = false
// HTTP 409 Conflict (with server's current state)
context.Response.StatusCode = 409;
}
}
catch (Exception ex)
{
// HTTP 500 Internal server error
context.Response.StatusCode = 500;
Program.ReportException(ex);
}
finally
{
// if this middleware didn't handle the request, pass it on
if(!context.Response.HasStarted)
await next(context);
}
}
public static void Broadcast(string message)
{
Console.WriteLine($"Broadcast: {message}");
foreach (var kvp in Clients)
kvp.Value.BroadcastQueue.Writer.TryWrite(message);
}
// event-handlers are the sole case where async void is valid
public static async void ApplicationShutdownHandler()
{
ServerIsRunning = false;
await CloseAllSocketsAsync();
}
private static async Task CloseAllSocketsAsync()
{
// We can't dispose the sockets until the processing loops are terminated,
// but terminating the loops will abort the sockets, preventing graceful closing.
var disposeQueue = new List<WebSocket>(Clients.Count);
while (Clients.Count > 0)
{
var client = Clients.ElementAt(0).Value;
Console.WriteLine($"Closing Socket {client.SocketId}");
Console.WriteLine("... ending broadcast loop");
client.BroadcastLoopTokenSource.Cancel();
if (client.Socket.State != WebSocketState.Open)
{
Console.WriteLine($"... socket not open, state = {client.Socket.State}");
}
else
{
var timeout = new CancellationTokenSource(Program.CLOSE_SOCKET_TIMEOUT_MS);
try
{
Console.WriteLine("... starting close handshake");
await client.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", timeout.Token);
}
catch (OperationCanceledException ex)
{
Program.ReportException(ex);
// normal upon task/token cancellation, disregard
}
}
if (Clients.TryRemove(client.SocketId, out _))
{
// only safe to Dispose once, so only add it if this loop can't process it again
disposeQueue.Add(client.Socket);
}
Console.WriteLine("... done");
}
// now that they're all closed, terminate the blocking ReceiveAsync calls in the SocketProcessingLoop threads
SocketLoopTokenSource.Cancel();
// dispose all resources
foreach (var socket in disposeQueue)
socket.Dispose();
}
private static async Task SocketProcessingLoopAsync(ConnectedClient client)
{
_ = Task.Run(() => client.BroadcastLoopAsync().ConfigureAwait(false));
var socket = client.Socket;
var loopToken = SocketLoopTokenSource.Token;
var broadcastTokenSource = client.BroadcastLoopTokenSource; // store a copy for use in finally block
try
{
var buffer = WebSocket.CreateServerBuffer(4096);
while (socket.State != WebSocketState.Closed && socket.State != WebSocketState.Aborted && !loopToken.IsCancellationRequested)
{
var receiveResult = await client.Socket.ReceiveAsync(buffer, loopToken);
// if the token is cancelled while ReceiveAsync is blocking, the socket state changes to aborted and it can't be used
if (!loopToken.IsCancellationRequested)
{
// the client is notifying us that the connection will close; send acknowledgement
if (client.Socket.State == WebSocketState.CloseReceived && receiveResult.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine($"Socket {client.SocketId}: Acknowledging Close frame received from client");
broadcastTokenSource.Cancel();
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None);
// the socket state changes to closed at this point
}
// echo text or binary data to the broadcast queue
if (client.Socket.State == WebSocketState.Open)
{
Console.WriteLine($"Socket {client.SocketId}: Received {receiveResult.MessageType} frame ({receiveResult.Count} bytes).");
Console.WriteLine($"Socket {client.SocketId}: Echoing data to queue.");
string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
client.BroadcastQueue.Writer.TryWrite(message);
}
}
}
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
catch (Exception ex)
{
Console.WriteLine($"Socket {client.SocketId}:");
Program.ReportException(ex);
}
finally
{
broadcastTokenSource.Cancel();
Console.WriteLine($"Socket {client.SocketId}: Ended processing loop in state {socket.State}");
// don't leave the socket in any potentially connected state
if (client.Socket.State != WebSocketState.Closed)
client.Socket.Abort();
// by this point the socket is closed or aborted, the ConnectedClient object is useless
if (Clients.TryRemove(client.SocketId, out _))
socket.Dispose();
// signal to the middleware pipeline that this task has completed
client.TaskCompletion.SetResult(true);
}
}
}
}