-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathBinaryTcpClient.cs
More file actions
2420 lines (2122 loc) · 80.7 KB
/
BinaryTcpClient.cs
File metadata and controls
2420 lines (2122 loc) · 80.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Foundation;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Streams;
#else
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
#endif
using Waher.Events;
using Waher.Networking.Sniffers;
using Waher.Security;
using Waher.Runtime.Collections;
namespace Waher.Networking
{
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also makes the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt. Outgoing data is queued and transmitted in the
/// permitted pace.
/// </summary>
public class BinaryTcpClient : CommunicationLayer, IDisposableAsync, IBinaryTransportLayer
{
private const int BufferSize = 65536;
private readonly ChunkedList<Rec> outputQueue = new ChunkedList<Rec>();
private ChunkedList<TaskCompletionSource<bool>> idleQueue = null;
private ChunkedList<TaskCompletionSource<bool>> cancelledQueue = null;
private ChunkedList<TaskCompletionSource<bool>> waitingQueue = null;
#if WINDOWS_UWP
private readonly MemoryBuffer memoryBuffer = new MemoryBuffer(BufferSize);
private readonly StreamSocket client;
private readonly IBuffer buffer = null;
private DataWriter dataWriter = null;
#else
private readonly byte[] buffer = new byte[BufferSize];
private readonly TcpClient tcpClient;
private readonly Guid id = Guid.NewGuid();
private Stream stream = null;
private CancellationTokenSource currentCancelReading;
#endif
private readonly object synchObj = new object();
private readonly bool sniffBinary;
private string hostName;
private string domainName;
private string remoteEndPoint = string.Empty;
private string localEndPoint = string.Empty;
private int outputQueueSize = 0;
private int maxOutputQueueSize = 2 * 65536; // 128 kB by default.
private bool connecting = false;
private bool connected = false;
private bool disposing = false;
private bool disposed = false;
private bool sending = false;
private bool reading = false;
private bool upgrading = false;
private bool trustRemoteEndPoint = false;
private bool remoteCertificateValid = false;
private bool disposeWhenDone = false;
private bool cancelRead = false;
private class Rec
{
public byte[] Data;
public int Offset;
public int Count;
public EventHandlerAsync<DeliveryEventArgs> Callback;
public object State;
public TaskCompletionSource<bool> Task;
}
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(bool DecoupledEvents, params ISniffer[] Sniffers)
: this(true, DecoupledEvents, Sniffers)
{
}
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="SniffBinary">If binary communication is to be forwarded to registered sniffers.</param>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(bool SniffBinary, bool DecoupledEvents, params ISniffer[] Sniffers)
: base(DecoupledEvents, Sniffers)
{
this.sniffBinary = SniffBinary;
#if WINDOWS_UWP
this.buffer = Windows.Storage.Streams.Buffer.CreateCopyFromMemoryBuffer(this.memoryBuffer);
this.client = new StreamSocket();
#else
this.tcpClient = new TcpClient();
#endif
}
#if WINDOWS_UWP
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="Client">Encapsulate this <see cref="TcpClient"/> connection.</param>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(StreamSocket Client, bool DecoupledEvents, params ISniffer[] Sniffers)
: this(Client, true, DecoupledEvents, Sniffers)
{
}
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="Client">Encapsulate this <see cref="TcpClient"/> connection.</param>
/// <param name="SniffBinary">If binary communication is to be forwarded to registered sniffers.</param>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(StreamSocket Client, bool SniffBinary, bool DecoupledEvents, params ISniffer[] Sniffers)
: base(DecoupledEvents, Sniffers)
{
this.sniffBinary = SniffBinary;
this.buffer = Windows.Storage.Streams.Buffer.CreateCopyFromMemoryBuffer(this.memoryBuffer);
this.client = Client;
this.SetTcpEndPoints();
}
private void SetTcpEndPoints()
{
if (this.remoteCertificate is null || !this.remoteCertificateValid)
this.remoteEndPoint = this.client.Information.RemoteAddress.ToString() + ":" + this.client.Information.RemotePort;
else
{
this.remoteEndPoint = GetDomainFromSubject(this.remoteCertificate.Subject);
if (string.IsNullOrEmpty(this.remoteEndPoint))
this.remoteEndPoint = this.client.Information.RemoteAddress.ToString() + ":" + this.client.Information.RemotePort;
}
this.localEndPoint = this.client.Information.LocalAddress.ToString() + ":" + this.client.Information.LocalPort;
}
#else
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="Client">Encapsulate this <see cref="TcpClient"/> connection.</param>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(TcpClient Client, bool DecoupledEvents, params ISniffer[] Sniffers)
: this(Client, true, DecoupledEvents, Sniffers)
{
}
/// <summary>
/// Implements a binary TCP Client, by encapsulating a <see cref="TcpClient"/>. It also maked the use of <see cref="TcpClient"/>
/// safe, making sure it can be disposed, even during an active connection attempt.
/// </summary>
/// <param name="Client">Encapsulate this <see cref="TcpClient"/> connection.</param>
/// <param name="SniffBinary">If binary communication is to be forwarded to registered sniffers.</param>
/// <param name="DecoupledEvents">If events raised from the communication
/// layer are decoupled, i.e. executed in parallel with the source that raised
/// them.</param>
/// <param name="Sniffers">Sniffers.</param>
public BinaryTcpClient(TcpClient Client, bool SniffBinary, bool DecoupledEvents, params ISniffer[] Sniffers)
: base(DecoupledEvents, Sniffers)
{
this.sniffBinary = SniffBinary;
this.tcpClient = Client;
this.SetTcpEndPoints();
}
private void SetTcpEndPoints()
{
Socket UnderlyingSocket = this.tcpClient.Client;
if (UnderlyingSocket is null)
return;
if (this.remoteCertificate is null || !this.remoteCertificateValid)
this.remoteEndPoint = UnderlyingSocket.RemoteEndPoint.ToString();
else
{
this.remoteEndPoint = GetDomainFromSubject(this.remoteCertificate.Subject);
if (string.IsNullOrEmpty(this.remoteEndPoint))
this.remoteEndPoint = UnderlyingSocket.RemoteEndPoint.ToString();
}
this.localEndPoint = UnderlyingSocket.LocalEndPoint.ToString();
}
#endif
/// <summary>
/// Extracts the domain name from a certificate subject string.
/// </summary>
/// <param name="Subject">Certificate subject string.</param>
/// <returns>Domain name, if available.</returns>
public static string GetDomainFromSubject(string Subject)
{
if (string.IsNullOrEmpty(Subject))
return string.Empty;
int i = Subject.IndexOf("CN=", StringComparison.InvariantCultureIgnoreCase);
if (i < 0)
return string.Empty;
i += 3;
int j = Subject.IndexOf(',', i);
if (j < 0)
return Subject.Substring(i).Trim();
else
return Subject.Substring(i, j - i).Trim();
}
#if WINDOWS_UWP
/// <summary>
/// Underlying <see cref="StreamSocket"/> object.
/// </summary>
public StreamSocket Client => this.client;
#else
/// <summary>
/// Underlying <see cref="TcpClient"/> object.
/// </summary>
public TcpClient Client => this.tcpClient;
/// <summary>
/// Stream object currently being used.
/// </summary>
public Stream Stream => this.stream;
#endif
/// <summary>
/// Remote End-point of connection. This corresponds to the IP Endpoint of the
/// remote party in normal cases. It can also be the domain name of the remote
/// party, if mTLS is used.
/// </summary>
public string RemoteEndPoint => this.remoteEndPoint;
/// <summary>
/// Local End-point of connection. This corresponds to the IP Endpoint of the
/// connection.
/// </summary>
public string LocalEndPoint => this.localEndPoint;
/// <summary>
/// Current output queue size, in bytes.
/// </summary>
public int OutputQueueSize
{
get
{
lock (this.synchObj)
{
return this.outputQueueSize;
}
}
}
/// <summary>
/// Maximum output queue size, in bytes.
/// </summary>
public int MaxOutputQueueSize
{
get
{
lock (this.synchObj)
{
return this.maxOutputQueueSize;
}
}
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("Max output queue size must be positive.", nameof(value));
lock (this.synchObj)
{
this.maxOutputQueueSize = value;
}
}
}
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Host">Host Name or IP Address in string format.</param>
/// <param name="Port">Port number.</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public Task<bool> ConnectAsync(string Host, int Port)
{
return this.ConnectAsync(Host, Port, false);
}
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Host">Host Name or IP Address in string format.</param>
/// <param name="Port">Port number.</param>
/// <param name="Paused">If connection starts in a paused state (i.e. not waiting for incoming communication).</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public async Task<bool> ConnectAsync(string Host, int Port, bool Paused)
{
this.hostName = this.domainName = Host;
this.PreConnect();
#if WINDOWS_UWP
await this.client.ConnectAsync(new HostName(Host), Port.ToString(), SocketProtectionLevel.PlainSocket);
return this.PostConnect(Paused);
#else
await this.tcpClient.ConnectAsync(Host, Port);
return this.PostConnect(Paused);
#endif
}
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Address">IP Address of the host.</param>
/// <param name="Port">Port number.</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public Task<bool> ConnectAsync(IPAddress Address, int Port)
{
return this.ConnectAsync(Address, Port, false);
}
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Address">IP Address of the host.</param>
/// <param name="Port">Port number.</param>
/// <param name="Paused">If connection starts in a paused state (i.e. not waiting for incoming communication).</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public async Task<bool> ConnectAsync(IPAddress Address, int Port, bool Paused)
{
this.hostName = this.domainName = Address.ToString();
this.PreConnect();
#if WINDOWS_UWP
await this.client.ConnectAsync(new HostName(Address.ToString()), Port.ToString(), SocketProtectionLevel.PlainSocket);
return this.PostConnect(Paused);
#else
await this.tcpClient.ConnectAsync(Address, Port);
return this.PostConnect(Paused);
#endif
}
#if !WINDOWS_UWP
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Addresses">IP Addresses of the host.</param>
/// <param name="Port">Port number.</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public Task<bool> ConnectAsync(IPAddress[] Addresses, int Port)
{
return this.ConnectAsync(Addresses, Port, false);
}
/// <summary>
/// Connects to a host using TCP.
/// </summary>
/// <param name="Addresses">IP Addresses of the host.</param>
/// <param name="Port">Port number.</param>
/// <param name="Paused">If connection starts in a paused state (i.e. not waiting for incoming communication).</param>
/// <returns>If connection was established. If false is returned, the object has been disposed during the connection attempt.</returns>
public async Task<bool> ConnectAsync(IPAddress[] Addresses, int Port, bool Paused)
{
this.hostName = this.domainName = null;
this.PreConnect();
await this.tcpClient.ConnectAsync(Addresses, Port);
return this.PostConnect(Paused);
}
#endif
/// <summary>
/// Binds to a <see cref="TcpClient"/> that was already connected when provided to the constructor.
/// </summary>
public void Bind()
{
this.Bind(false);
}
/// <summary>
/// Binds to a <see cref="TcpClient"/> that was already connected when provided to the constructor.
/// </summary>
/// <param name="Paused">If connection starts in a paused state (i.e. not waiting for incoming communication).</param>
public void Bind(bool Paused)
{
this.PreConnect();
this.PostConnect(Paused);
}
/// <summary>
/// If the connection is open.
/// </summary>
public bool Connected => this.connected && !this.disposing && !this.disposed;
#if WINDOWS_UWP
/// <summary>
/// Current Cancellation token for the current read operation.
/// </summary>
public CancellationToken CurrentCancellationToken => CancellationToken.None;
#else
/// <summary>
/// Current Cancellation token for the current read operation.
/// </summary>
public CancellationToken CurrentCancellationToken => this.currentCancelReading?.Token ?? CancellationToken.None;
#endif
private void PreConnect()
{
lock (this.synchObj)
{
if (this.connecting)
throw new InvalidOperationException("Connection attempt already underway.");
if (this.connected)
throw new InvalidOperationException("Already connected.");
if (this.disposing || this.disposed)
throw new ObjectDisposedException("Object has been disposed.");
this.connecting = true;
}
this.remoteCertificate = null;
this.remoteCertificateValid = false;
}
private bool PostConnect(bool Paused)
{
bool Disposing = false;
lock (this.synchObj)
{
this.connecting = false;
if (this.disposed)
return false;
if (this.disposing)
Disposing = true;
else
this.connected = true;
}
if (Disposing)
{
Task.Run(async () =>
{
try
{
await this.DoDisposeAsyncLocked();
}
catch (Exception ex)
{
Log.Exception(ex);
}
});
return false;
}
#if WINDOWS_UWP
this.dataWriter = new DataWriter(this.client.OutputStream);
#else
this.stream = this.tcpClient.GetStream();
#endif
if (!Paused)
this.BeginRead();
return true;
}
/// <summary>
/// Disposes the client when done sending all data.
/// </summary>
public void DisposeWhenDone()
{
lock (this.synchObj)
{
if (this.connected && this.sending)
{
this.disposeWhenDone = true;
return;
}
}
Task.Run(() =>
{
try
{
this.DisposeAsync();
}
catch (Exception ex)
{
Log.Exception(ex);
}
});
}
/// <summary>
/// Disposes of the object. The underlying <see cref="TcpClient"/> is either disposed directly, or when asynchronous
/// operations have ceased.
/// </summary>
[Obsolete("Use DisposeAsync() instead.")]
public void Dispose()
{
Task.Run(() => this.DisposeAsync());
}
/// <summary>
/// Disposes of the object asynchronously. The underlying <see cref="TcpClient"/> is
/// either disposed directly, or when asynchronous operations have ceased.
/// </summary>
public virtual Task DisposeAsync()
{
#if WINDOWS_UWP
bool Cancel;
bool DoDispose = false;
lock (this.synchObj)
{
if (this.disposed || this.disposing)
return Task.CompletedTask;
if (Cancel = this.connecting || this.reading || this.sending)
this.disposing = true;
else
DoDispose = true;
}
if (Cancel)
{
IAsyncAction _ = this.client.CancelIOAsync();
}
if (DoDispose)
return this.DoDisposeAsyncLocked();
else
return Task.CompletedTask;
}
#else
bool DelayedDispose;
lock (this.synchObj)
{
if (this.disposed || this.disposing)
return Task.CompletedTask;
if (this.connecting || this.reading || this.sending)
{
this.disposing = true;
#if !WINDOWS_UWP
this.currentCancelReading?.Cancel();
#endif
DelayedDispose = true;
}
else
DelayedDispose = false;
}
#if !WINDOWS_UWP
CancellationTokenSource Cancel = this.currentCancelReading;
this.currentCancelReading = null;
Cancel?.Dispose();
NetworkingModule.UnregisterToken(this.id);
#endif
if (DelayedDispose)
{
Task.Delay(1000).ContinueWith(this.AbortRead); // Double-check socket gets cancelled. If not, forcefully close.
return Task.CompletedTask;
}
else
return this.DoDisposeAsyncLocked();
}
private Task AbortRead(object P)
{
if (this.disposed)
return Task.CompletedTask;
else
return this.DoDisposeAsyncLocked();
}
#endif
private async Task DoDisposeAsyncLocked()
{
this.disposed = true;
this.connecting = false;
this.connected = false;
await this.CancelOutputQueue();
this.outputQueue.Clear();
this.outputQueueSize = 0;
lock (this.synchObj)
{
this.EmptyIdleQueueLocked();
this.EmptyCancelQueueLocked();
}
#if WINDOWS_UWP
this.client.Dispose();
this.memoryBuffer.Dispose();
this.dataWriter.Dispose();
#else
this.stream = null;
this.tcpClient.Dispose();
this.remoteCertificate?.Dispose();
this.remoteCertificate = null;
#endif
if (this.HasSniffers)
await this.RemoveRange(this.Sniffers, true);
}
/// <summary>
/// Continues reading from the socket, if paused in an event handler.
/// </summary>
public void Continue()
{
this.BeginRead();
}
/// <summary>
/// If the reading is paused.
/// </summary>
public bool Paused
{
get
{
lock (this.synchObj)
{
return this.connected && !this.reading;
}
}
}
private async void BeginRead() // Starts parallel task
{
lock (this.synchObj)
{
if (this.disposing || this.disposed || this.reading)
return;
this.reading = true;
}
#if WINDOWS_UWP
IInputStream InputStream;
#else
Stream Stream;
#endif
int NrRead;
bool Continue = true;
try
{
while (Continue)
{
lock (this.synchObj)
{
if (this.disposing || this.disposed || this.cancelRead || NetworkingModule.Stopping)
break;
#if WINDOWS_UWP
InputStream = this.client.InputStream;
if (InputStream is null)
break;
#else
Stream = this.stream;
if (Stream is null)
break;
#endif
}
#if WINDOWS_UWP
IBuffer DataRead = await InputStream.ReadAsync(this.buffer, BufferSize, InputStreamOptions.Partial);
if (DataRead.Length == 0)
break;
CryptographicBuffer.CopyToByteArray(DataRead, out byte[] Packet);
if (Packet is null)
break;
NrRead = Packet.Length;
#else
CancellationTokenSource PrevCancel = this.currentCancelReading;
this.currentCancelReading = new CancellationTokenSource();
NetworkingModule.RegisterToken(this.id, this.currentCancelReading);
PrevCancel?.Dispose();
NrRead = await Stream.ReadAsync(this.buffer, 0, BufferSize, this.currentCancelReading?.Token ?? CancellationToken.None);
#endif
if (this.disposing || this.disposed || NetworkingModule.Stopping)
break;
if (NrRead <= 0)
{
lock (this.synchObj)
{
if (this.cancelRead)
break;
}
await this.Disconnected();
break;
}
try
{
#if WINDOWS_UWP
Continue = await this.BinaryDataReceived(false, Packet, 0, NrRead);
#else
Continue = await this.BinaryDataReceived(false, this.buffer, 0, NrRead);
#endif
}
catch (Exception ex)
{
this.Exception(ex);
}
}
}
catch (Exception ex)
{
this.Exception(ex);
}
finally
{
bool Disposing = false;
#if !WINDOWS_UWP
CancellationTokenSource Cancel = this.currentCancelReading;
this.currentCancelReading = null;
Cancel?.Cancel();
Cancel?.Dispose();
NetworkingModule.UnregisterToken(this.id);
#endif
lock (this.synchObj)
{
this.reading = false;
if (this.cancelRead)
{
this.cancelRead = false;
this.EmptyCancelQueueLocked();
}
if (this.disposing && !this.sending)
Disposing = true;
}
if (Disposing)
await this.DoDisposeAsyncLocked();
}
if (!Continue && !this.disposed && !this.disposing)
await this.OnPaused.Raise(this, EventArgs.Empty, false);
}
/// <summary>
/// Event raised when reading on the socked has been paused. Call <see cref="Continue"/> to resume reading.
/// </summary>
public event EventHandlerAsync OnPaused;
/// <summary>
/// Clears the <see cref="OnPaused"/> event handler.
/// </summary>
public void OnPausedClear() => this.OnPaused = null;
/// <summary>
/// Resets the <see cref="OnPaused"/> event handler.
/// </summary>
/// <param name="EventHandler">Event handler to set.</param>
public void OnPausedReset(EventHandlerAsync EventHandler) => this.OnPaused = EventHandler;
/// <summary>
/// Method called when the connection has been disconnected.
/// </summary>
protected virtual Task Disconnected()
{
if (!(this.OnDisconnected is null))
return this.OnDisconnected.Raise(this, EventArgs.Empty);
else
return Task.CompletedTask;
}
/// <summary>
/// Method called when binary data has been received.
/// </summary>
/// <param name="ConstantBuffer">If the contents of the buffer remains constant (true),
/// or if the contents in the buffer may change after the call (false).</param>
/// <param name="Buffer">Binary Data Buffer</param>
/// <param name="Offset">Start index of first byte read.</param>
/// <param name="Count">Number of bytes read.</param>
/// <returns>If the process should be continued.</returns>
protected virtual async Task<bool> BinaryDataReceived(bool ConstantBuffer,
byte[] Buffer, int Offset, int Count)
{
if (this.sniffBinary && this.HasSniffers)
this.ReceiveBinary(ConstantBuffer, Buffer, Offset, Count);
BinaryDataReadEventHandler h = this.OnReceived;
if (h is null)
return true;
else
return await h(this, ConstantBuffer, Buffer, Offset, Count);
}
/// <summary>
/// Method called when an exception has been caught.
/// </summary>
/// <param name="Timestamp">Timestamp of event.</param>
/// <param name="ex">Exception</param>
public override void Exception(DateTime Timestamp, Exception ex)
{
try
{
base.Exception(Timestamp, ex);
}
catch (Exception ex2)
{
Log.Exception(ex2);
}
EventHandlerAsync<Exception> h = this.OnError;
if (!(h is null))
{
Task.Run(async () =>
{
try
{
await h(this, ex);
}
catch (Exception ex2)
{
Log.Exception(ex2);
}
});
}
}
/// <summary>
/// Event received when binary data has been received.
/// </summary>
public event BinaryDataReadEventHandler OnReceived;
/// <summary>
/// Clears the <see cref="OnReceived"/> event handler.
/// </summary>
public void OnReceivedClear() => this.OnReceived = null;
/// <summary>
/// Resets the <see cref="OnReceived"/> event handler.
/// </summary>
/// <param name="EventHandler">Event handler to set.</param>
public void OnReceivedReset(BinaryDataReadEventHandler EventHandler) => this.OnReceived = EventHandler;
/// <summary>
/// Event raised when an error has occurred.
/// </summary>
public event EventHandlerAsync<Exception> OnError;
/// <summary>
/// Clears the <see cref="OnError"/> event handler.
/// </summary>
public void OnErrorClear() => this.OnError = null;
/// <summary>
/// Resets the <see cref="OnError"/> event handler.
/// </summary>
/// <param name="EventHandler">Event handler to set.</param>
public void OnErrorReset(EventHandlerAsync<Exception> EventHandler) => this.OnError = EventHandler;
/// <summary>
/// Event raised when the connection has been disconnected.
/// </summary>
public event EventHandlerAsync OnDisconnected;
/// <summary>
/// Clears the <see cref="OnDisconnected"/> event handler.
/// </summary>
public void OnDisconnectedClear() => this.OnDisconnected = null;
/// <summary>
/// Resets the <see cref="OnDisconnected"/> event handler.
/// </summary>
/// <param name="EventHandler">Event handler to set.</param>
public void OnDisconnectedReset(EventHandlerAsync EventHandler) => this.OnDisconnected = EventHandler;
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="Packet">Binary packet.</param>
/// <returns>If data was sent.</returns>
[Obsolete("Use an overload with a ConstantBuffer argument. This increases performance, as the buffer will not be unnecessarily cloned if queued.")]
public Task<bool> SendAsync(byte[] Packet)
{
return this.SendAsync(false, Packet, 0, Packet.Length, false, null, null);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="ConstantBuffer">If the contents of the buffer remains constant (true),
/// or if the contents in the buffer may change after the call (false).</param>
/// <param name="Packet">Binary packet.</param>
/// <returns>If data was sent.</returns>
public Task<bool> SendAsync(bool ConstantBuffer, byte[] Packet)
{
return this.SendAsync(ConstantBuffer, Packet, 0, Packet.Length, false, null, null);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="Packet">Binary packet.</param>
/// <param name="Priority">If packet should be sent before any waiting in the queue.</param>
/// <returns>If data was sent.</returns>
[Obsolete("Use an overload with a ConstantBuffer argument. This increases performance, as the buffer will not be unnecessarily cloned if queued.")]
public Task<bool> SendAsync(byte[] Packet, bool Priority)
{
return this.SendAsync(false, Packet, 0, Packet.Length, Priority, null, null);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="ConstantBuffer">If the contents of the buffer remains constant (true),
/// or if the contents in the buffer may change after the call (false).</param>
/// <param name="Packet">Binary packet.</param>
/// <param name="Priority">If packet should be sent before any waiting in the queue.</param>
/// <returns>If data was sent.</returns>
public Task<bool> SendAsync(bool ConstantBuffer, byte[] Packet, bool Priority)
{
return this.SendAsync(ConstantBuffer, Packet, 0, Packet.Length, Priority, null, null);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="Packet">Binary packet.</param>
/// <param name="Callback">Method to call when packet has been sent.</param>
/// <param name="State">State object to pass on to callback method.</param>
/// <returns>If data was sent.</returns>
[Obsolete("Use an overload with a ConstantBuffer argument. This increases performance, as the buffer will not be unnecessarily cloned if queued.")]
public Task<bool> SendAsync(byte[] Packet, EventHandlerAsync<DeliveryEventArgs> Callback, object State)
{
return this.SendAsync(false, Packet, 0, Packet.Length, false, Callback, State);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="ConstantBuffer">If the contents of the buffer remains constant (true),
/// or if the contents in the buffer may change after the call (false).</param>
/// <param name="Packet">Binary packet.</param>
/// <param name="Callback">Method to call when packet has been sent.</param>
/// <param name="State">State object to pass on to callback method.</param>
/// <returns>If data was sent.</returns>
public Task<bool> SendAsync(bool ConstantBuffer, byte[] Packet, EventHandlerAsync<DeliveryEventArgs> Callback, object State)
{
return this.SendAsync(ConstantBuffer, Packet, 0, Packet.Length, false, Callback, State);
}
/// <summary>
/// Sends a binary packet.
/// </summary>
/// <param name="Packet">Binary packet.</param>
/// <param name="Priority">If packet should be sent before any waiting in the queue.</param>
/// <param name="Callback">Method to call when packet has been sent.</param>