forked from MV10/WebSocketExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketServer.cs
More file actions
237 lines (214 loc) · 10.7 KB
/
Copy pathWebSocketServer.cs
File metadata and controls
237 lines (214 loc) · 10.7 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketExample
{
public static class WebSocketServer
{
// note that Microsoft plans to deprecate HttpListener,
// and for .NET Core they don't even support SSL/TLS
// https://github.com/dotnet/platform-compat/issues/88
private static HttpListener Listener;
private static CancellationTokenSource SocketLoopTokenSource;
private static CancellationTokenSource ListenerLoopTokenSource;
private static int SocketCounter = 0;
private static bool ServerIsRunning = true;
// The key is a socket id
private static ConcurrentDictionary<int, ConnectedClient> Clients = new ConcurrentDictionary<int, ConnectedClient>();
public static void Start(string uriPrefix)
{
SocketLoopTokenSource = new CancellationTokenSource();
ListenerLoopTokenSource = new CancellationTokenSource();
Listener = new HttpListener();
Listener.Prefixes.Add(uriPrefix);
Listener.Start();
if (Listener.IsListening)
{
Console.WriteLine("Connect browser for a basic echo-back web page.");
Console.WriteLine($"Server listening: {uriPrefix}");
// listen on a separate thread so that Listener.Stop can interrupt GetContextAsync
Task.Run(() => ListenerProcessingLoopAsync().ConfigureAwait(false));
}
else
{
Console.WriteLine("Server failed to start.");
}
}
public static async Task StopAsync()
{
if (Listener?.IsListening ?? false && ServerIsRunning)
{
Console.WriteLine("\nServer is stopping.");
ServerIsRunning = false; // prevent new connections during shutdown
await CloseAllSocketsAsync(); // also cancels processing loop tokens (abort ReceiveAsync)
ListenerLoopTokenSource.Cancel(); // safe to stop now that sockets are closed
Listener.Stop();
Listener.Close();
}
}
private static async Task ListenerProcessingLoopAsync()
{
var cancellationToken = ListenerLoopTokenSource.Token;
try
{
while (!cancellationToken.IsCancellationRequested)
{
HttpListenerContext context = await Listener.GetContextAsync();
if (ServerIsRunning)
{
if (context.Request.IsWebSocketRequest)
{
// HTTP is only the initial connection; upgrade to a client-specific websocket
HttpListenerWebSocketContext wsContext = null;
try
{
wsContext = await context.AcceptWebSocketAsync(subProtocol: null);
int socketId = Interlocked.Increment(ref SocketCounter);
var client = new ConnectedClient(socketId, wsContext.WebSocket);
Clients.TryAdd(socketId, client);
Console.WriteLine($"Socket {socketId}: New connection.");
_ = Task.Run(() => SocketProcessingLoopAsync(client).ConfigureAwait(false));
}
catch (Exception)
{
// server error if upgrade from HTTP to WebSocket fails
context.Response.StatusCode = 500;
context.Response.StatusDescription = "WebSocket upgrade failed";
context.Response.Close();
return;
}
}
else
{
if (context.Request.AcceptTypes.Contains("text/html"))
{
Console.WriteLine("Sending HTML to client.");
ReadOnlyMemory<byte> HtmlPage = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(SimpleHtmlClient.HTML));
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
context.Response.ContentLength64 = HtmlPage.Length;
await context.Response.OutputStream.WriteAsync(HtmlPage, CancellationToken.None);
await context.Response.OutputStream.FlushAsync(CancellationToken.None);
}
else
{
context.Response.StatusCode = 400;
}
context.Response.Close();
}
}
else
{
// HTTP 409 Conflict (with server's current state)
context.Response.StatusCode = 409;
context.Response.StatusDescription = "Server is shutting down";
context.Response.Close();
return;
}
}
}
catch (HttpListenerException ex) when (ServerIsRunning)
{
Program.ReportException(ex);
}
}
private static async Task SocketProcessingLoopAsync(ConnectedClient client)
{
var socket = client.Socket;
var loopToken = SocketLoopTokenSource.Token;
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");
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 client.");
await socket.SendAsync(new ArraySegment<byte>(buffer.Array, 0, receiveResult.Count), receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
}
}
}
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
catch (Exception ex)
{
Console.WriteLine($"Socket {client.SocketId}:");
Program.ReportException(ex);
}
finally
{
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();
}
}
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");
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();
}
}
}