-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkServer.cs
More file actions
593 lines (476 loc) · 18.7 KB
/
Copy pathNetworkServer.cs
File metadata and controls
593 lines (476 loc) · 18.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Caching;
using System.Threading;
namespace Server
{
public class NetworkServer : IDisposable
{
private readonly Func<MessageContext, MessageResponse> _messageHandler;
private readonly ConcurrentDictionary<EndPoint, Socket> _clientSockets;
private readonly ConcurrentDictionary<EndPoint, Guid> _clientSessions;
private readonly ConcurrentDictionary<EndPoint, AvailabilityNotifier> _clientNotifiers;
private static ConcurrentQueue<List<ArraySegment<byte>>> _BufferPool;
private readonly Timer _poolTimer;
private readonly Func<byte[], List<ArraySegment<byte>>> _bufferServer = GetBuffer;
private int _timesPoolEmpty;
private Socket _listenSocket;
public event EventHandler<SocketErrorArgs> SocketErrorEncountered;
public event EventHandler<MessageResponse> EndpointSocketNotFound;
public event EventHandler<EndPoint> FailedAddingClient;
public event EventHandler<EndPoint> FailedGeneratingSession;
public event EventHandler<EndPoint> FailedWatchingClient;
public event EventHandler<Guid> SessionClosed;
public event EventHandler HighUsageAlert;
private event EventHandler<Tuple<Socket, int>> CouldNotAddClient;
private event EventHandler<Tuple<Socket, int>> CouldNotGenerateSession;
private event EventHandler<Tuple<AvailabilityNotifier, int>> CouldNotWatchClient;
private readonly MemoryCache _disposalCache;
/// <summary>
/// Instantiates a new instance of the <c>NetworkServer</c>.
/// </summary>
/// <param name="endpoint">The endpoint, address and port combination, over which the <c>NetworkServer</c> will communicate.</param>
/// <param name="messageHandler">A <c>Func</c> object that will process incoming messages and be responsible for generating responses.</param>
/// <param name="bufferPoolSize">The number of buffers that are available for socket operations.</param>
/// <param name="bufferSize">The size of each buffer in the pool.</param>
public NetworkServer(EndPoint endpoint, Func<MessageContext, MessageResponse> messageHandler, int bufferPoolSize, int bufferSize)
{
ConfigureListenSocket(endpoint);
_messageHandler = messageHandler;
_clientSockets = new ConcurrentDictionary<EndPoint, Socket>();
_clientSessions = new ConcurrentDictionary<EndPoint, Guid>();
_clientNotifiers = new ConcurrentDictionary<EndPoint, AvailabilityNotifier>();
_BufferPool = new ConcurrentQueue<List<ArraySegment<byte>>>();
BuildBufferPool(bufferPoolSize, bufferSize);
_poolTimer = new Timer(BalanceBufferPool, new Tuple<int, int>(bufferPoolSize, bufferSize), TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(500));
CouldNotAddClient += CouldNotAddClientHandler;
CouldNotGenerateSession += CouldNotGenerateSessionHandler;
CouldNotWatchClient += CouldNotWatchClientHandler;
_disposalCache = new MemoryCache("Disposal");
}
private void BuildBufferPool(int bufferPoolSize, int bufferSize)
{
Enumerable.Range(1, bufferPoolSize).AsParallel()
.ForAll(i =>
{
_BufferPool.Enqueue(new List<ArraySegment<byte>> {new ArraySegment<byte>(new byte[bufferSize])});
});
}
private void BalanceBufferPool(object state)
{
var tuple = (Tuple<int, int>) state;
var poolSize = tuple.Item1;
var bufferSize = tuple.Item2;
if (_BufferPool.Count == 0)
{
Interlocked.Increment(ref _timesPoolEmpty);
}
if (_timesPoolEmpty > 3)
{
if (_BufferPool.Count > poolSize * 10)
{
OnHighUsageAlert();
return;
}
BuildBufferPool(poolSize, bufferSize);
Interlocked.Exchange(ref _timesPoolEmpty, 0);
}
while (_BufferPool.Count > poolSize)
{
_BufferPool.TryDequeue(out List<ArraySegment<byte>> list);
}
}
private void ConfigureListenSocket(EndPoint endpoint)
{
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
{
ExclusiveAddressUse = false,
LingerState = new LingerOption(true, 5),
NoDelay = true,
Blocking = false
};
_listenSocket.Bind(endpoint);
}
public void Start()
{
_listenSocket.Listen(int.MaxValue);
ThreadPool.QueueUserWorkItem(AcceptAsync);
}
private void AcceptAsync(object state)
{
var args = new SocketAsyncEventArgs();
args.Completed += Accept_Completed;
if (!_listenSocket.AcceptAsync(args))
{
CompleteAccept(args);
}
}
private void CompleteAccept(SocketAsyncEventArgs args)
{
ThreadPool.QueueUserWorkItem(AcceptAsync);
if (args.SocketError != SocketError.Success)
{
if (args.SocketError == SocketError.ConnectionReset)
{
CleanUpClient(args.ConnectSocket);
return;
}
OnSocketErrorEncountered(new SocketErrorArgs
{
SocketEndPoint = args.RemoteEndPoint,
Error = args.SocketError,
Source = SocketEventSource.Accept
});
}
SetupNewClient(args);
}
private void SetupNewClient(SocketAsyncEventArgs args)
{
var socket = args.AcceptSocket;
try
{
if (!_clientSockets.TryAdd(socket.RemoteEndPoint, socket))
{
OnCouldNotAddClient(new Tuple<Socket, int>(socket, 1));
}
if (!_clientSessions.TryAdd(socket.RemoteEndPoint, Guid.NewGuid()))
{
OnCouldNotGenerateSession(new Tuple<Socket, int>(socket, 1));
}
}
catch (ArgumentNullException)
{
return;
}
var watcher = new AvailabilityNotifier(socket, ref _BufferPool, _bufferServer);
watcher.DataAvailable += Client_DataAvailable;
watcher.Disconnected += Client_Disconnected;
if (_clientNotifiers.TryAdd(socket.RemoteEndPoint, watcher))
{
watcher.BeginWatching();
}
else
{
OnCouldNotWatchClient(new Tuple<AvailabilityNotifier, int>(watcher, 1));
}
}
private void Client_Disconnected(object sender, Socket e)
{
ThreadPool.QueueUserWorkItem(CleanUpClient, e);
}
private void Client_DataAvailable(object sender, Socket e)
{
var buffer = GetBuffer();
var args = new SocketAsyncEventArgs
{
BufferList = buffer,
UserToken = e
};
args.Completed += Receive_Completed;
try
{
if (!e.ReceiveAsync(args))
{
CompleteReceive(args);
}
}
catch (ObjectDisposedException)
{
}
}
private static List<ArraySegment<byte>> GetBuffer(byte[] prefillData = null)
{
List<ArraySegment<byte>> buffer;
while (!_BufferPool.TryDequeue(out buffer))
{
Thread.Sleep(250);
}
var array = buffer.First().Array;
if (array == null)
{
throw new InvalidOperationException("A fetched buffer has an internal array that was null.");
}
Array.Clear(array, 0, array.Length);
if (prefillData != null)
{
if (prefillData.Length > array.Length)
{
throw new InvalidOperationException("The prefill array contains more data than the fetched buffer was configured to allow.");
}
Array.Copy(prefillData, array, prefillData.Length);
}
return buffer;
}
private void CompleteReceive(SocketAsyncEventArgs args)
{
EndPoint endpoint;
Socket socket;
try
{
socket = (Socket) args.UserToken;
endpoint = socket.RemoteEndPoint;
}
catch (ObjectDisposedException)
{
return;
}
if (args.SocketError != SocketError.Success)
{
if (args.SocketError == SocketError.ConnectionReset)
{
CleanUpClient(args.UserToken);
return;
}
OnSocketErrorEncountered(new SocketErrorArgs
{
SocketEndPoint = endpoint,
Error = args.SocketError,
Source = SocketEventSource.Receive
});
}
if (args.BytesTransferred == 0)
{
CleanUpClient(socket);
return;
}
_clientSessions.TryGetValue(endpoint, out Guid sessionId);
var receiveBuffer = new byte[args.BytesTransferred];
Array.Copy(args.BufferList.First().Array, receiveBuffer, receiveBuffer.Length);
_BufferPool.Enqueue(args.BufferList.ToList());
_messageHandler.BeginInvoke(
new MessageContext
{
SessionId = sessionId,
ReceivedOn = endpoint,
Request = receiveBuffer
}, MessageHandlerComplete, _messageHandler);
}
private void MessageHandlerComplete(IAsyncResult ar)
{
var handler = (Func<MessageContext, MessageResponse>)ar.AsyncState;
var response = handler.EndInvoke(ar);
ThreadPool.QueueUserWorkItem(SendToSocket, response);
}
private void SendToSocket(object state)
{
var response = (MessageResponse)state;
_clientSockets.TryGetValue(response.Context.ReceivedOn, out Socket client);
if (client == null)
{
OnEndpointSocketNotFound(response);
return;
}
var buffer = new List<ArraySegment<byte>> {new ArraySegment<byte>(response.Body)};
var args = new SocketAsyncEventArgs
{
BufferList = buffer,
UserToken = client
};
args.Completed += Send_Completed;
try
{
if (!client.SendAsync(args))
{
CompleteSend(args);
}
}
catch (ObjectDisposedException)
{
}
}
private void CompleteSend(SocketAsyncEventArgs args)
{
if (args.SocketError != SocketError.Success)
{
var socket = (Socket) args.UserToken;
if (args.SocketError == SocketError.ConnectionAborted || args.SocketError == SocketError.ConnectionReset || args.SocketError == SocketError.Shutdown)
{
CleanUpClient(socket);
return;
}
OnSocketErrorEncountered(new SocketErrorArgs
{
SocketEndPoint = socket.RemoteEndPoint,
Error = args.SocketError,
Source = SocketEventSource.Send
});
}
_BufferPool.Enqueue(args.BufferList.ToList());
}
private void Send_Completed(object sender, SocketAsyncEventArgs e)
{
CompleteSend(e);
}
private void CleanUpClient(object state)
{
var stateSocket = (Socket) state;
if (stateSocket == null || _disposalCache.Contains(stateSocket.Handle.ToString()))
{
return;
}
try
{
var endpoint = stateSocket.RemoteEndPoint;
_clientNotifiers.TryRemove(endpoint, out AvailabilityNotifier notifier);
_clientSockets.TryRemove(endpoint, out Socket socket);
_clientSessions.TryRemove(endpoint, out Guid sessionId);
socket.Shutdown(SocketShutdown.Both);
socket.Close(5);
notifier.Dispose();
OnSessionClosed(sessionId);
}
catch
{
// ignored
}
finally
{
var cacheItem = new CacheItem(stateSocket.Handle.ToString(), stateSocket);
var cachePolicy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1)};
_disposalCache.Add(cacheItem, cachePolicy);
}
}
private void Receive_Completed(object sender, SocketAsyncEventArgs e)
{
CompleteReceive(e);
}
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
CompleteAccept(e);
}
private void CouldNotAddClientHandler(object sender, Tuple<Socket, int> e)
{
var socket = e.Item1;
var attempts = e.Item2;
if (attempts >= 3)
{
OnFailedAddingClient(socket.RemoteEndPoint);
return;
}
if (!_clientSockets.TryAdd(socket.RemoteEndPoint, socket))
{
OnCouldNotAddClient(new Tuple<Socket, int>(socket, attempts + 1));
}
}
private void CouldNotGenerateSessionHandler(object sender, Tuple<Socket, int> e)
{
var socket = e.Item1;
var attempts = e.Item2;
if (attempts >= 3)
{
OnFailedGeneratingSession(socket.RemoteEndPoint);
return;
}
if (!_clientSessions.TryAdd(socket.RemoteEndPoint, Guid.NewGuid()))
{
OnCouldNotGenerateSession(new Tuple<Socket, int>(socket, attempts + 1));
}
}
private void CouldNotWatchClientHandler(object sender, Tuple<AvailabilityNotifier, int> e)
{
var watcher = e.Item1;
var attempts = e.Item2;
if (attempts >= 3)
{
OnFailedWatchingClient(watcher.Target.RemoteEndPoint);
return;
}
if (_clientNotifiers.TryAdd(watcher.Target.RemoteEndPoint, watcher))
{
watcher.BeginWatching();
}
else
{
OnCouldNotWatchClient(new Tuple<AvailabilityNotifier, int>(watcher, attempts + 1));
}
}
protected virtual void OnSocketErrorEncountered(SocketErrorArgs e)
{
SocketErrorEncountered?.BeginInvoke(this, e, EndInvokeSocketError, SocketErrorEncountered);
}
private void EndInvokeSocketError(IAsyncResult ar)
{
var socketError = (EventHandler<SocketErrorArgs>) ar.AsyncState;
socketError.EndInvoke(ar);
}
protected virtual void OnEndpointSocketNotFound(MessageResponse e)
{
EndpointSocketNotFound?.BeginInvoke(this, e, EndInvokeMessageResponse, EndpointSocketNotFound);
}
private void EndInvokeMessageResponse(IAsyncResult ar)
{
var messageResponse = (EventHandler<MessageResponse>) ar.AsyncState;
messageResponse.EndInvoke(ar);
}
protected virtual void OnCouldNotAddClient(Tuple<Socket, int> e)
{
CouldNotAddClient?.BeginInvoke(this, e, EndInvokeSocketInt, CouldNotAddClient);
}
private void EndInvokeSocketInt(IAsyncResult ar)
{
var socketInt = (EventHandler<Tuple<Socket, int>>) ar.AsyncState;
socketInt.EndInvoke(ar);
}
protected virtual void OnFailedAddingClient(EndPoint e)
{
FailedAddingClient?.BeginInvoke(this, e, EndInvokeEndpoint, FailedAddingClient);
}
private void EndInvokeEndpoint(IAsyncResult ar)
{
var endpoint = (EventHandler<EndPoint>) ar.AsyncState;
endpoint.EndInvoke(ar);
}
protected virtual void OnCouldNotGenerateSession(Tuple<Socket, int> e)
{
CouldNotGenerateSession?.BeginInvoke(this, e, EndInvokeSocketInt, CouldNotGenerateSession);
}
protected virtual void OnFailedGeneratingSession(EndPoint e)
{
FailedGeneratingSession?.BeginInvoke(this, e, EndInvokeEndpoint, FailedGeneratingSession);
}
protected virtual void OnCouldNotWatchClient(Tuple<AvailabilityNotifier, int> e)
{
CouldNotWatchClient?.BeginInvoke(this, e, EndInvokeNotifierInt, CouldNotWatchClient);
}
private void EndInvokeNotifierInt(IAsyncResult ar)
{
var notifierInt = (EventHandler<Tuple<AvailabilityNotifier, int>>) ar.AsyncState;
notifierInt.EndInvoke(ar);
}
protected virtual void OnFailedWatchingClient(EndPoint e)
{
FailedWatchingClient?.BeginInvoke(this, e, EndInvokeEndpoint, FailedWatchingClient);
}
protected virtual void OnSessionClosed(Guid e)
{
SessionClosed?.BeginInvoke(this, e, EndInvokeGuid, SessionClosed);
}
private void EndInvokeGuid(IAsyncResult ar)
{
var guid = (EventHandler<Guid>) ar.AsyncState;
guid.EndInvoke(ar);
}
protected virtual void OnHighUsageAlert()
{
HighUsageAlert?.BeginInvoke(this, EventArgs.Empty, EndInvoke, HighUsageAlert);
}
private void EndInvoke(IAsyncResult ar)
{
var handler = (EventHandler)ar.AsyncState;
handler.EndInvoke(ar);
}
public void Dispose()
{
_listenSocket.Shutdown(SocketShutdown.Both);
_listenSocket.Close(1);
_listenSocket?.Dispose();
_disposalCache.Dispose();
_poolTimer.Dispose();
GC.SuppressFinalize(this);
}
}
}