-
Notifications
You must be signed in to change notification settings - Fork 180
/
AsyncTcpSocketClient.cs
591 lines (510 loc) · 23.7 KB
/
AsyncTcpSocketClient.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
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
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Cowboy.Buffer;
using Logrila.Logging;
namespace Cowboy.Sockets
{
public class AsyncTcpSocketClient
{
#region Fields
private static readonly ILog _log = Logger.Get<AsyncTcpSocketClient>();
private TcpClient _tcpClient;
private readonly IAsyncTcpSocketClientEventDispatcher _dispatcher;
private readonly AsyncTcpSocketClientConfiguration _configuration;
private readonly IPEndPoint _remoteEndPoint;
private readonly IPEndPoint _localEndPoint;
private Stream _stream;
private ArraySegment<byte> _receiveBuffer = default(ArraySegment<byte>);
private int _receiveBufferOffset = 0;
private int _state;
private const int _none = 0;
private const int _connecting = 1;
private const int _connected = 2;
private const int _closed = 5;
#endregion
#region Constructors
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort, IPAddress localAddress, int localPort, IAsyncTcpSocketClientEventDispatcher dispatcher, AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort), new IPEndPoint(localAddress, localPort), dispatcher, configuration)
{
}
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort, IPEndPoint localEP, IAsyncTcpSocketClientEventDispatcher dispatcher, AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort), localEP, dispatcher, configuration)
{
}
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort, IAsyncTcpSocketClientEventDispatcher dispatcher, AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort), dispatcher, configuration)
{
}
public AsyncTcpSocketClient(IPEndPoint remoteEP, IAsyncTcpSocketClientEventDispatcher dispatcher, AsyncTcpSocketClientConfiguration configuration = null)
: this(remoteEP, null, dispatcher, configuration)
{
}
public AsyncTcpSocketClient(IPEndPoint remoteEP, IPEndPoint localEP, IAsyncTcpSocketClientEventDispatcher dispatcher, AsyncTcpSocketClientConfiguration configuration = null)
{
if (remoteEP == null)
throw new ArgumentNullException("remoteEP");
if (dispatcher == null)
throw new ArgumentNullException("dispatcher");
_remoteEndPoint = remoteEP;
_localEndPoint = localEP;
_dispatcher = dispatcher;
_configuration = configuration ?? new AsyncTcpSocketClientConfiguration();
if (_configuration.BufferManager == null)
throw new InvalidProgramException("The buffer manager in configuration cannot be null.");
if (_configuration.FrameBuilder == null)
throw new InvalidProgramException("The frame handler in configuration cannot be null.");
}
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort, IPAddress localAddress, int localPort,
Func<AsyncTcpSocketClient, byte[], int, int, Task> onServerDataReceived = null,
Func<AsyncTcpSocketClient, Task> onServerConnected = null,
Func<AsyncTcpSocketClient, Task> onServerDisconnected = null,
AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort), new IPEndPoint(localAddress, localPort),
onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
{
}
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort, IPEndPoint localEP,
Func<AsyncTcpSocketClient, byte[], int, int, Task> onServerDataReceived = null,
Func<AsyncTcpSocketClient, Task> onServerConnected = null,
Func<AsyncTcpSocketClient, Task> onServerDisconnected = null,
AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort), localEP,
onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
{
}
public AsyncTcpSocketClient(IPAddress remoteAddress, int remotePort,
Func<AsyncTcpSocketClient, byte[], int, int, Task> onServerDataReceived = null,
Func<AsyncTcpSocketClient, Task> onServerConnected = null,
Func<AsyncTcpSocketClient, Task> onServerDisconnected = null,
AsyncTcpSocketClientConfiguration configuration = null)
: this(new IPEndPoint(remoteAddress, remotePort),
onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
{
}
public AsyncTcpSocketClient(IPEndPoint remoteEP,
Func<AsyncTcpSocketClient, byte[], int, int, Task> onServerDataReceived = null,
Func<AsyncTcpSocketClient, Task> onServerConnected = null,
Func<AsyncTcpSocketClient, Task> onServerDisconnected = null,
AsyncTcpSocketClientConfiguration configuration = null)
: this(remoteEP, null,
onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
{
}
public AsyncTcpSocketClient(IPEndPoint remoteEP, IPEndPoint localEP,
Func<AsyncTcpSocketClient, byte[], int, int, Task> onServerDataReceived = null,
Func<AsyncTcpSocketClient, Task> onServerConnected = null,
Func<AsyncTcpSocketClient, Task> onServerDisconnected = null,
AsyncTcpSocketClientConfiguration configuration = null)
: this(remoteEP, localEP,
new DefaultAsyncTcpSocketClientEventDispatcher(onServerDataReceived, onServerConnected, onServerDisconnected),
configuration)
{
}
#endregion
#region Properties
public TimeSpan ConnectTimeout { get { return _configuration.ConnectTimeout; } }
private bool Connected { get { return _tcpClient != null && _tcpClient.Client.Connected; } }
public IPEndPoint RemoteEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.RemoteEndPoint : _remoteEndPoint; } }
public IPEndPoint LocalEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.LocalEndPoint : _localEndPoint; } }
public TcpSocketConnectionState State
{
get
{
switch (_state)
{
case _none:
return TcpSocketConnectionState.None;
case _connecting:
return TcpSocketConnectionState.Connecting;
case _connected:
return TcpSocketConnectionState.Connected;
case _closed:
return TcpSocketConnectionState.Closed;
default:
return TcpSocketConnectionState.Closed;
}
}
}
public override string ToString()
{
return string.Format("RemoteEndPoint[{0}], LocalEndPoint[{1}]",
this.RemoteEndPoint, this.LocalEndPoint);
}
#endregion
#region Connect
public async Task Connect()
{
int origin = Interlocked.Exchange(ref _state, _connecting);
if (!(origin == _none || origin == _closed))
{
await Close(false); // connecting with wrong state
throw new InvalidOperationException("This tcp socket client is in invalid state when connecting.");
}
Clean(); // force to clean
try
{
_tcpClient = _localEndPoint != null ?
new TcpClient(_localEndPoint) :
new TcpClient(_remoteEndPoint.Address.AddressFamily);
SetSocketOptions();
var awaiter = _tcpClient.ConnectAsync(_remoteEndPoint.Address, _remoteEndPoint.Port);
if (!awaiter.Wait(ConnectTimeout))
{
await Close(false); // connect timeout
throw new TimeoutException(string.Format(
"Connect to [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
}
var negotiator = NegotiateStream(_tcpClient.GetStream());
if (!negotiator.Wait(ConnectTimeout))
{
await Close(false); // ssl negotiation timeout
throw new TimeoutException(string.Format(
"Negotiate SSL/TSL with remote [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
}
_stream = negotiator.Result;
if (_receiveBuffer == default(ArraySegment<byte>))
_receiveBuffer = _configuration.BufferManager.BorrowBuffer();
_receiveBufferOffset = 0;
if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
{
await Close(false); // connected with wrong state
throw new InvalidOperationException("This tcp socket client is in invalid state when connected.");
}
_log.DebugFormat("Connected to server [{0}] with dispatcher [{1}] on [{2}].",
this.RemoteEndPoint,
_dispatcher.GetType().Name,
DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"));
bool isErrorOccurredInUserSide = false;
try
{
await _dispatcher.OnServerConnected(this);
}
catch (Exception ex) // catch all exceptions from out-side
{
isErrorOccurredInUserSide = true;
await HandleUserSideError(ex);
}
if (!isErrorOccurredInUserSide)
{
Task.Factory.StartNew(async () =>
{
await Process();
},
TaskCreationOptions.None)
.Forget();
}
else
{
await Close(true); // user side handle tcp connection error occurred
}
}
catch (Exception ex) // catch exceptions then log then re-throw
{
_log.Error(ex.Message, ex);
await Close(true); // handle tcp connection error occurred
throw;
}
}
private async Task Process()
{
try
{
int frameLength;
byte[] payload;
int payloadOffset;
int payloadCount;
int consumedLength = 0;
while (State == TcpSocketConnectionState.Connected)
{
int receiveCount = await _stream.ReadAsync(
_receiveBuffer.Array,
_receiveBuffer.Offset + _receiveBufferOffset,
_receiveBuffer.Count - _receiveBufferOffset);
if (receiveCount == 0)
break;
SegmentBufferDeflector.ReplaceBuffer(_configuration.BufferManager, ref _receiveBuffer, ref _receiveBufferOffset, receiveCount);
consumedLength = 0;
while (true)
{
frameLength = 0;
payload = null;
payloadOffset = 0;
payloadCount = 0;
if (_configuration.FrameBuilder.Decoder.TryDecodeFrame(
_receiveBuffer.Array,
_receiveBuffer.Offset + consumedLength,
_receiveBufferOffset - consumedLength,
out frameLength, out payload, out payloadOffset, out payloadCount))
{
try
{
await _dispatcher.OnServerDataReceived(this, payload, payloadOffset, payloadCount);
}
catch (Exception ex) // catch all exceptions from out-side
{
await HandleUserSideError(ex);
}
finally
{
consumedLength += frameLength;
}
}
else
{
break;
}
}
if (_receiveBuffer != null && _receiveBuffer.Array != null)
{
SegmentBufferDeflector.ShiftBuffer(_configuration.BufferManager, consumedLength, ref _receiveBuffer, ref _receiveBufferOffset);
}
}
}
catch (ObjectDisposedException)
{
// looking forward to a graceful quit from the ReadAsync but the inside EndRead will raise the ObjectDisposedException,
// so a gracefully close for the socket should be a Shutdown, but we cannot avoid the Close triggers this happen.
}
catch (Exception ex)
{
await HandleReceiveOperationException(ex);
}
finally
{
await Close(true); // read async buffer returned, remote notifies closed
}
}
private void SetSocketOptions()
{
_tcpClient.ReceiveBufferSize = _configuration.ReceiveBufferSize;
_tcpClient.SendBufferSize = _configuration.SendBufferSize;
_tcpClient.ReceiveTimeout = (int)_configuration.ReceiveTimeout.TotalMilliseconds;
_tcpClient.SendTimeout = (int)_configuration.SendTimeout.TotalMilliseconds;
_tcpClient.NoDelay = _configuration.NoDelay;
_tcpClient.LingerState = _configuration.LingerState;
if (_configuration.KeepAlive)
{
_tcpClient.Client.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.KeepAlive,
(int)_configuration.KeepAliveInterval.TotalMilliseconds);
}
_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, _configuration.ReuseAddress);
}
private async Task<Stream> NegotiateStream(Stream stream)
{
if (!_configuration.SslEnabled)
return stream;
var validateRemoteCertificate = new RemoteCertificateValidationCallback(
(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
=>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (_configuration.SslPolicyErrorsBypassed)
return true;
else
_log.ErrorFormat("Error occurred when validating remote certificate: [{0}], [{1}].",
this.RemoteEndPoint, sslPolicyErrors);
return false;
});
var sslStream = new SslStream(
stream,
false,
validateRemoteCertificate,
null,
_configuration.SslEncryptionPolicy);
if (_configuration.SslClientCertificates == null || _configuration.SslClientCertificates.Count == 0)
{
await sslStream.AuthenticateAsClientAsync( // No client certificates are used in the authentication. The certificate revocation list is not checked during authentication.
_configuration.SslTargetHost); // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
}
else
{
await sslStream.AuthenticateAsClientAsync(
_configuration.SslTargetHost, // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
_configuration.SslClientCertificates, // The X509CertificateCollection that contains client certificates.
_configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
_configuration.SslCheckCertificateRevocation); // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
}
// When authentication succeeds, you must check the IsEncrypted and IsSigned properties
// to determine what security services are used by the SslStream.
// Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
_log.DebugFormat(
"Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
+ "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
sslStream.SslProtocol,
sslStream.IsServer,
sslStream.IsAuthenticated,
sslStream.IsEncrypted,
sslStream.IsSigned,
sslStream.IsMutuallyAuthenticated,
sslStream.HashAlgorithm,
sslStream.HashStrength,
sslStream.KeyExchangeAlgorithm,
sslStream.KeyExchangeStrength,
sslStream.CipherAlgorithm,
sslStream.CipherStrength);
return sslStream;
}
#endregion
#region Close
public async Task Close()
{
await Close(true); // close by external
}
private async Task Close(bool shallNotifyUserSide)
{
if (Interlocked.Exchange(ref _state, _closed) == _closed)
{
return;
}
Shutdown();
if (shallNotifyUserSide)
{
_log.DebugFormat("Disconnected from server [{0}] with dispatcher [{1}] on [{2}].",
this.RemoteEndPoint,
_dispatcher.GetType().Name,
DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"));
try
{
await _dispatcher.OnServerDisconnected(this);
}
catch (Exception ex) // catch all exceptions from out-side
{
await HandleUserSideError(ex);
}
}
Clean();
}
public void Shutdown()
{
// The correct way to shut down the connection (especially if you are in a full-duplex conversation)
// is to call socket.Shutdown(SocketShutdown.Send) and give the remote party some time to close
// their send channel. This ensures that you receive any pending data instead of slamming the
// connection shut. ObjectDisposedException should never be part of the normal application flow.
if (_tcpClient != null && _tcpClient.Connected)
{
_tcpClient.Client.Shutdown(SocketShutdown.Send);
}
}
private void Clean()
{
try
{
try
{
if (_stream != null)
{
_stream.Dispose();
}
}
catch { }
try
{
if (_tcpClient != null)
{
_tcpClient.Close();
}
}
catch { }
}
catch { }
finally
{
_stream = null;
_tcpClient = null;
}
if (_receiveBuffer != default(ArraySegment<byte>))
_configuration.BufferManager.ReturnBuffer(_receiveBuffer);
_receiveBuffer = default(ArraySegment<byte>);
_receiveBufferOffset = 0;
}
#endregion
#region Exception Handler
private async Task HandleSendOperationException(Exception ex)
{
if (IsSocketTimeOut(ex))
{
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
}
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, ex);
}
private async Task HandleReceiveOperationException(Exception ex)
{
if (IsSocketTimeOut(ex))
{
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
}
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, ex);
}
private bool IsSocketTimeOut(Exception ex)
{
return ex is IOException
&& ex.InnerException != null
&& ex.InnerException is SocketException
&& (ex.InnerException as SocketException).SocketErrorCode == SocketError.TimedOut;
}
private async Task<bool> CloseIfShould(Exception ex)
{
if (ex is ObjectDisposedException
|| ex is InvalidOperationException
|| ex is SocketException
|| ex is IOException
|| ex is NullReferenceException // buffer array operation
|| ex is ArgumentException // buffer array operation
)
{
_log.Error(ex.Message, ex);
await Close(false); // intend to close the session
return true;
}
return false;
}
private async Task HandleUserSideError(Exception ex)
{
_log.Error(string.Format("Client [{0}] error occurred in user side [{1}].", this, ex.Message), ex);
await Task.CompletedTask;
}
#endregion
#region Send
public async Task SendAsync(byte[] data)
{
await SendAsync(data, 0, data.Length);
}
public async Task SendAsync(byte[] data, int offset, int count)
{
BufferValidator.ValidateBuffer(data, offset, count, "data");
if (State != TcpSocketConnectionState.Connected)
{
throw new InvalidOperationException("This client has not connected to server.");
}
try
{
byte[] frameBuffer;
int frameBufferOffset;
int frameBufferLength;
_configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);
await _stream.WriteAsync(frameBuffer, frameBufferOffset, frameBufferLength);
}
catch (Exception ex)
{
await HandleSendOperationException(ex);
}
}
#endregion
}
}