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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
|
using Hazel.Dtls;
using Hazel.Udp;
using Hazel.Udp.FewerThreads;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace Hazel.UnitTests.Dtls
{
[TestClass]
public class DtlsConnectionTests
{
// Created with command line
// openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 100000 -out certificate.pem
const string TestCertificate =
@"-----BEGIN CERTIFICATE-----
MIIDbTCCAlWgAwIBAgIUREHeZ36f23eBFQ1T3sJsBwHlSBEwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yMTAyMDIxNDE4MTBaGA8yMjk0
MTExODE0MTgxMFowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAMeHCR6Y6GFwH7ZnouxPLmqyCIJSCcfaGIuBU3k+
MG2ZyXKhhhwclL8arx5x1cGmQFvPm5wXGKSiLFChj+bW5XN7xBAc5e9KVBCEabrr
BY+X9r0a421Yjqn4F47IA2sQ6OygnttYIt0pgeEoQZhGvmc2ZfkELkptIHMavIsx
B/R0tYgtquruWveIWMtr4O/AuPxkH750SO1OxwU8gj6QXSqskrxvhl9GBzAwBKaF
W6t7yjR7eFqaGh7B55p4t5zrfYKCVgeyj5Yzr/xdvv3Q3H+0pex+JTMWrpsTaavq
F2RZYbpTOofuiTwdWbAHnXW1aFSCCIrEdEs9X2FxB73V0fcCAwEAAaNTMFEwHQYD
VR0OBBYEFETIkxnzoLXO2GcEgxTZgN8ypKowMB8GA1UdIwQYMBaAFETIkxnzoLXO
2GcEgxTZgN8ypKowMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB
ACZl7WQec9xLTK0paBIkVUqZKucDCXQH0JC7z4ENbiRtQvWQm6xhAlDo8Tr8oUzj
0/lft/g6wIo8dJ4jZ/iCSHnKz8qO80Gs/x5NISe9A/8Us1kq8y4nO40QW6xtQMH7
j74pcfsGKDCaMFSQZnSc93a3ZMEuVPxdI5+qsvFIeC9xxRHUNo245eLqsJAe8s1c
22Uoeu3gepozrPcIPAHADGr/CFp1HLkg9nFrTcatlNAF/N0PmLjmk/NIx/8h7n7Q
5vapNkhcyCHsW8XB5ulKmF88QZ5BdvPmtSey0t/n8ru98615G5Wb4TS2MaprzYL3
5ACeQOohFzevcQrEjjzkZAI=
-----END CERTIFICATE-----
";
const string TestPrivateKey =
@"-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHhwkemOhhcB+2
Z6LsTy5qsgiCUgnH2hiLgVN5PjBtmclyoYYcHJS/Gq8ecdXBpkBbz5ucFxikoixQ
oY/m1uVze8QQHOXvSlQQhGm66wWPl/a9GuNtWI6p+BeOyANrEOjsoJ7bWCLdKYHh
KEGYRr5nNmX5BC5KbSBzGryLMQf0dLWILarq7lr3iFjLa+DvwLj8ZB++dEjtTscF
PII+kF0qrJK8b4ZfRgcwMASmhVure8o0e3hamhoeweeaeLec632CglYHso+WM6/8
Xb790Nx/tKXsfiUzFq6bE2mr6hdkWWG6UzqH7ok8HVmwB511tWhUggiKxHRLPV9h
cQe91dH3AgMBAAECggEAVq+jVajHJTYqgPwLu7E3EGHi8oOj/jESAuIgGwfa0HNF
I0lr06DTOyfjt01ruiN5yKmtCKa8LSLMMAfRVlA9BexapUl42HqphTeSHARpuRYj
u8sHzgTwjoXb7kuVuJlzKQMroU5sbzvOUr1Dql3p8TugGA0p82nv9DJEghC+TQT2
GnCKhsnmwE7lb8h0z3G3yxdv3yZE0X6oFzllBGCb1O6cwsDeYsv+SyjnyUwJROGz
/VkC1+B48ALm4DhA5QIUoaRhO8vaCa7dacQTkXw1hVdLcaS9slIdXxbb9GbJvI0c
baqimIkE02VUUpmlOIKUpf1sRXy1aJFpDSvWsTNLaQKBgQD8TrcVUF7oOhX5hQer
qfNDFPvCBiWlT+8tnJraauaD1sJLD5jpRWPDu5dZ96CSZVpD1E3GQm+x58CSUknG
AUHyHfEHTpzx7elVeUj7gianmVu8r9mVKtErwPLDJ4AUhMJjEPX2Plmh9GgFck78
s2gfIvxdI+znvkH9JwGBznTIRQKBgQDKcpO7wiu025ZyPWR2p+qUh2ZlvBBr/6rg
GxbFE5VraIS6zSDVOcxjPLc1pVZ/vM2WGbda0eziLpvsyauTXMCueBiNBRWZb5E4
NK81IgbgZc4VWN9xA00cfOzO4Bjt6990BdOxiQQ1XOz1cN8DFTfsA81qR+nIne58
LhL0DmFLCwKBgCwsU92FbrhVwxcmdUtWu+JYwCMeFGU283cW3f2zjZwzc1zU5D6j
CW5xX3Q+6Hv5Bq6tcthtNUT+gDad9ZCXE8ah+1r+Jngs4Rc33tE53i6lqOwGFaAK
GQkCBP6p4cC15ZqWk5mDHQo/0h5x/uY7OtWIuIpOCeIg60i5FYh2bvfJAoGAPQ7t
i7V2ZSfNaksl37upPn7P3WMpOMl1if3hkjLj3+84CPcRLf4urMeFIkLpocEZ6Gl9
KYEjBtyz3mi8vMc+veAu12lvKEXD8MXDCi1nEYri6wFQ8s7iFPOAoKxqGGgJjv6q
6GLAyC9ssGIIgO+HXEGRVLq3wfAQG5fx03X61h0CgYEAiz3f8xiIR6PC4Gn5iMWu
wmIDk3EnxdaA+7AwN/M037jbmKfzLxA1n8jXYM+to4SJx8Fxo7MD5EDhq6UoYmPU
tGe4Ite2N9jzxG7xQrVuIx6Cg4t+E7uZ1eZuhbQ1WpqCXPIFOtXuc4szXfwD4Z+p
IsdbLCwHYD3GVgk/D7NVxyU=
-----END PRIVATE KEY-----
";
private static X509Certificate2 GetCertificateForServer()
{
RSA privateKey = Utils.DecodeRSAKeyFromPEM(TestPrivateKey);
return new X509Certificate2(Utils.DecodePEM(TestCertificate)).CopyWithPrivateKey(privateKey);
}
private static X509Certificate2Collection GetCertificateForClient()
{
X509Certificate2 publicCertificate = new X509Certificate2(Utils.DecodePEM(TestCertificate));
X509Certificate2Collection clientCertificates = new X509Certificate2Collection();
clientCertificates.Add(publicCertificate);
return clientCertificates;
}
protected DtlsConnectionListener CreateListener(int numWorkers, IPEndPoint endPoint, ILogger logger, IPMode ipMode = IPMode.IPv4)
{
DtlsConnectionListener listener = new DtlsConnectionListener(2, endPoint, logger, ipMode);
listener.SetCertificate(GetCertificateForServer());
return listener;
}
protected DtlsUnityConnection CreateConnection(IPEndPoint endPoint, ILogger logger, IPMode ipMode = IPMode.IPv4)
{
DtlsUnityConnection connection = new DtlsUnityConnection(logger, endPoint, ipMode);
connection.SetValidServerCertificates(GetCertificateForClient());
return connection;
}
[TestMethod]
public void DtlsServerDisposeDisconnectsTest()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 27510);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
Semaphore signal = new Semaphore(0, int.MaxValue);
using (var listener = (DtlsConnectionListener)CreateListener(2, new IPEndPoint(IPAddress.Any, ep.Port), new TestLogger()))
using (var connection = CreateConnection(ep, new TestLogger()))
{
listener.NewConnection += (evt) =>
{
serverConnected = true;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
serverDisconnected = true;
};
};
connection.Disconnected += (o, evt) => {
clientDisconnected = true;
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
listener.Dispose();
// wait for the client to disconnect
signal.WaitOne(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
Assert.AreEqual(0, listener.PeerCount);
}
}
class MalformedDTLSListener : DtlsConnectionListener
{
public MalformedDTLSListener(int numWorkers, IPEndPoint endPoint, ILogger logger, IPMode ipMode = IPMode.IPv4)
: base(numWorkers, endPoint, logger, ipMode)
{
}
public void InjectPacket(ByteSpan packet, IPEndPoint peerAddress, ConnectionId connectionId)
{
MessageReader reader = MessageReader.GetSized(packet.Length);
reader.Length = packet.Length;
Array.Copy(packet.GetUnderlyingArray(), packet.Offset, reader.Buffer, reader.Offset, packet.Length);
base.ProcessIncomingMessageFromOtherThread(reader, peerAddress, connectionId);
}
}
class MalformedDTLSClient : DtlsUnityConnection
{
public Func<ClientHello, ByteSpan, ByteSpan> EncodeClientHelloCallback = Test_CompressionLengthOverrunClientHello;
public MalformedDTLSClient(ILogger logger, IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base(logger, remoteEndPoint, ipMode)
{
}
protected override void SendClientHello(bool isResend)
{
Test_SendClientHello(EncodeClientHelloCallback);
}
public static ByteSpan Test_CompressionLengthOverrunClientHello(ClientHello clientHello, ByteSpan writer)
{
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)ProtocolVersion.DTLS1_2);
writer = writer.Slice(2);
clientHello.Random.CopyTo(writer);
writer = writer.Slice(Hazel.Dtls.Random.Size);
// Do not encode session ids
writer[0] = (byte)0;
writer = writer.Slice(1);
writer[0] = (byte)clientHello.Cookie.Length;
clientHello.Cookie.CopyTo(writer.Slice(1));
writer = writer.Slice(1 + clientHello.Cookie.Length);
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)clientHello.CipherSuites.Length);
clientHello.CipherSuites.CopyTo(writer.Slice(2));
writer = writer.Slice(2 + clientHello.CipherSuites.Length);
// ============ Here is the corruption. writer[0] should be 1. ============
writer[0] = 255;
writer[1] = (byte)CompressionMethod.Null;
writer = writer.Slice(2);
// Extensions size
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)(6 + clientHello.SupportedCurves.Length));
writer = writer.Slice(2);
// Supported curves extension
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)ExtensionType.EllipticCurves);
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)(2 + clientHello.SupportedCurves.Length), 2);
ByteSpanBigEndianExtensions.WriteBigEndian16(writer, (ushort)clientHello.SupportedCurves.Length, 4);
clientHello.SupportedCurves.CopyTo(writer.Slice(6));
return writer;
}
}
[TestMethod]
public void TestMalformedApplicationData()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 27510);
IPEndPoint connectionEndPoint = ep;
DtlsConnectionListener.ConnectionId connectionId = new ThreadLimitedUdpConnectionListener.ConnectionId();
Semaphore signal = new Semaphore(0, int.MaxValue);
using (MalformedDTLSListener listener = new MalformedDTLSListener(2, new IPEndPoint(IPAddress.Any, ep.Port), new TestLogger()))
using (DtlsUnityConnection connection = new DtlsUnityConnection(new TestLogger(), ep))
{
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
connectionEndPoint = evt.Connection.EndPoint;
connectionId = ((ThreadLimitedUdpServerConnection)evt.Connection).ConnectionId;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
};
};
connection.Disconnected += (o, evt) => {
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
ByteSpan data = new byte[5] { 0x01, 0x02, 0x03, 0x04, 0x05 };
Record record = new Record();
record.ContentType = ContentType.ApplicationData;
record.ProtocolVersion = ProtocolVersion.DTLS1_2;
record.Epoch = 1;
record.SequenceNumber = 10;
record.Length = (ushort)data.Length;
ByteSpan encoded = new byte[Record.Size + data.Length];
record.Encode(encoded);
data.CopyTo(encoded.Slice(Record.Size));
listener.InjectPacket(encoded, connectionEndPoint, connectionId);
// wait for the client to disconnect
listener.Dispose();
signal.WaitOne(100);
}
}
[TestMethod]
public void TestMalformedConnectionData()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 27510);
IPEndPoint connectionEndPoint = ep;
DtlsConnectionListener.ConnectionId connectionId = new ThreadLimitedUdpConnectionListener.ConnectionId();
Semaphore signal = new Semaphore(0, int.MaxValue);
using (DtlsConnectionListener listener = new DtlsConnectionListener(2, new IPEndPoint(IPAddress.Any, ep.Port), new TestLogger()))
using (MalformedDTLSClient connection = new MalformedDTLSClient(new TestLogger(), ep))
{
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
connectionEndPoint = evt.Connection.EndPoint;
connectionId = ((ThreadLimitedUdpServerConnection)evt.Connection).ConnectionId;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
};
};
connection.Disconnected += (o, evt) => {
signal.Release();
};
listener.Start();
connection.Connect();
Assert.IsTrue(listener.ReceiveThreadRunning, "Listener should be able to handle a malformed hello packet");
Assert.AreEqual(ConnectionState.NotConnected, connection.State);
Assert.AreEqual(0, listener.PeerCount);
// wait for the client to disconnect
listener.Dispose();
signal.WaitOne(100);
}
}
[TestMethod]
public void TestReorderedHandshakePacketsConnects()
{
IPEndPoint captureEndPoint = new IPEndPoint(IPAddress.Loopback, 27511);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Loopback, 27510);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
Semaphore signal = new Semaphore(0, int.MaxValue);
var logger = new TestLogger("Throttle");
using (SocketCapture capture = new SocketCapture(captureEndPoint, listenerEndPoint, logger))
using (DtlsConnectionListener listener = new DtlsConnectionListener(2, new IPEndPoint(IPAddress.Any, listenerEndPoint.Port), new TestLogger("Server")))
using (DtlsUnityConnection connection = new DtlsUnityConnection(new TestLogger("Client "), captureEndPoint))
{
Semaphore listenerToConnectionThrottle = new Semaphore(0, int.MaxValue);
capture.SendToLocalSemaphore = listenerToConnectionThrottle;
Thread throttleThread = new Thread(() => {
// HelloVerifyRequest
capture.AssertPacketsToLocalCountEquals(1);
listenerToConnectionThrottle.Release(1);
// ServerHello, Server Certificate (Fragment)
// Server Cert
// ServerKeyExchange, ServerHelloDone
capture.AssertPacketsToLocalCountEquals(3);
capture.ReorderPacketsForLocal(list => list.Swap(0, 1));
listenerToConnectionThrottle.Release(3);
capture.AssertPacketsToLocalCountEquals(0);
// Same flight, let's swap the ServerKeyExchange to the front
capture.AssertPacketsToLocalCountEquals(3);
capture.ReorderPacketsForLocal(list => list.Swap(0, 2));
listenerToConnectionThrottle.Release(3);
capture.AssertPacketsToLocalCountEquals(0);
// Same flight, no swap we do matters as long as the ServerKeyExchange gets through.
capture.AssertPacketsToLocalCountEquals(3);
capture.ReorderPacketsForLocal(list => list.Reverse());
capture.SendToLocalSemaphore = null;
listenerToConnectionThrottle.Release(1);
});
throttleThread.Start();
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
serverConnected = true;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
serverDisconnected = true;
};
};
connection.Disconnected += (o, evt) => {
clientDisconnected = true;
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
listener.Dispose();
// wait for the client to disconnect
signal.WaitOne(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
}
}
[TestMethod]
public void TestResentClientHelloConnects()
{
IPEndPoint captureEndPoint = new IPEndPoint(IPAddress.Loopback, 27511);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Loopback, 27510);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
Semaphore signal = new Semaphore(0, int.MaxValue);
var logger = new TestLogger("Throttle");
using (SocketCapture capture = new SocketCapture(captureEndPoint, listenerEndPoint, logger))
using (DtlsConnectionListener listener = new DtlsConnectionListener(2, new IPEndPoint(IPAddress.Any, listenerEndPoint.Port), new TestLogger("Server")))
using (DtlsUnityConnection connection = new DtlsUnityConnection(new TestLogger("Client "), captureEndPoint))
{
Semaphore listenerToConnectionThrottle = new Semaphore(0, int.MaxValue);
capture.SendToLocalSemaphore = listenerToConnectionThrottle;
Thread throttleThread = new Thread(() => {
// Trigger resend of HelloVerifyRequest
capture.DiscardPacketForLocal();
capture.AssertPacketsToLocalCountEquals(1);
listenerToConnectionThrottle.Release(1);
// ServerHello, ServerCertificate
// ServerCertificate
// ServerKeyExchange, ServerHelloDone
capture.AssertPacketsToLocalCountEquals(3);
listenerToConnectionThrottle.Release(3);
// Trigger a resend of ServerKeyExchange, ServerHelloDone
capture.DiscardPacketForLocal();
// From here, flush everything. We recover or not.
capture.SendToLocalSemaphore = null;
listenerToConnectionThrottle.Release(1);
});
throttleThread.Start();
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
serverConnected = true;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
serverDisconnected = true;
};
};
connection.Disconnected += (o, evt) => {
clientDisconnected = true;
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
listener.Dispose();
// wait for the client to disconnect
signal.WaitOne(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
}
}
[TestMethod]
public void TestResentServerHelloConnects()
{
IPEndPoint captureEndPoint = new IPEndPoint(IPAddress.Loopback, 27511);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Loopback, 27510);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
Semaphore signal = new Semaphore(0, int.MaxValue);
using (SocketCapture capture = new SocketCapture(captureEndPoint, listenerEndPoint))
using (DtlsConnectionListener listener = new DtlsConnectionListener(2, new IPEndPoint(IPAddress.Any, listenerEndPoint.Port), new TestLogger("Server")))
using (DtlsUnityConnection connection = new DtlsUnityConnection(new TestLogger("Client "), captureEndPoint))
{
Semaphore listenerToConnectionThrottle = new Semaphore(0, int.MaxValue);
capture.SendToLocalSemaphore = listenerToConnectionThrottle;
Thread throttleThread = new Thread(() => {
// HelloVerifyRequest
capture.AssertPacketsToLocalCountEquals(1);
listenerToConnectionThrottle.Release(1);
// ServerHello, Server Certificate
// Server Certificate
// ServerKeyExchange, ServerHelloDone
capture.AssertPacketsToLocalCountEquals(3);
capture.DiscardPacketForLocal();
listenerToConnectionThrottle.Release(2);
// Wait for the resends and recover
capture.AssertPacketsToLocalCountEquals(3);
capture.SendToLocalSemaphore = null;
listenerToConnectionThrottle.Release(3);
});
throttleThread.Start();
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
serverConnected = true;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
serverDisconnected = true;
};
};
connection.Disconnected += (o, evt) => {
clientDisconnected = true;
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
listener.Dispose();
// wait for the client to disconnect
signal.WaitOne(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
}
}
[TestMethod]
public void TestConnectionSuccessAfterClientKeyExchangeFlightDropped()
{
IPEndPoint captureEndPoint = new IPEndPoint(IPAddress.Loopback, 27511);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Loopback, 27510);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
Semaphore signal = new Semaphore(0, int.MaxValue);
using (SocketCapture capture = new SocketCapture(captureEndPoint, listenerEndPoint))
using (DtlsConnectionListener listener = new DtlsConnectionListener(2, new IPEndPoint(IPAddress.Any, listenerEndPoint.Port), new TestLogger()))
using (TestDtlsHandshakeDropUnityConnection connection = new TestDtlsHandshakeDropUnityConnection(new TestLogger(), captureEndPoint))
{
connection.DropSendClientKeyExchangeFlightCount = 1;
listener.SetCertificate(GetCertificateForServer());
connection.SetValidServerCertificates(GetCertificateForClient());
listener.NewConnection += (evt) =>
{
serverConnected = true;
signal.Release();
evt.Connection.Disconnected += (o, et) => {
serverDisconnected = true;
};
};
connection.Disconnected += (o, evt) => {
clientDisconnected = true;
signal.Release();
};
listener.Start();
connection.Connect();
// wait for the client to connect
signal.WaitOne(10);
listener.Dispose();
// wait for the client to disconnect
signal.WaitOne(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
}
}
/// <summary>
/// Tests the keepalive functionality from the client,
/// </summary>
[TestMethod]
public void PingDisconnectClientTest()
{
#if DEBUG
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 27510);
using (DtlsConnectionListener listener = (DtlsConnectionListener)CreateListener(2, new IPEndPoint(IPAddress.Any, ep.Port), new TestLogger()))
{
// Adjust the ping rate to end the test faster
listener.NewConnection += (evt) =>
{
var conn = (ThreadLimitedUdpServerConnection)evt.Connection;
conn.KeepAliveInterval = 100;
conn.MissingPingsUntilDisconnect = 3;
};
listener.Start();
for (int i = 0; i < 5; ++i)
{
using (DtlsUnityConnection connection = (DtlsUnityConnection)CreateConnection(ep, new TestLogger()))
{
connection.KeepAliveInterval = 100;
connection.MissingPingsUntilDisconnect = 3;
connection.Connect();
Thread.Sleep(10);
// After connecting, quietly stop responding to all messages to fake connection loss.
connection.TestDropRate = 1;
Thread.Sleep(500); //Enough time for ~3 keep alive packets
Assert.AreEqual(ConnectionState.NotConnected, connection.State);
}
}
listener.DisconnectOldConnections(TimeSpan.FromMilliseconds(500), null);
Assert.AreEqual(0, listener.PeerCount, "All clients disconnected, peer count should be zero.");
}
#else
Assert.Inconclusive("Only works in DEBUG");
#endif
}
[TestMethod]
public void ServerDisposeDisconnectsTest()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger("SERVER")))
using (UdpConnection connection = this.CreateConnection(ep, new TestLogger("CLIENT")))
{
listener.NewConnection += (evt) =>
{
serverConnected = true;
evt.Connection.Disconnected += (o, et) => serverDisconnected = true;
};
connection.Disconnected += (o, evt) => clientDisconnected = true;
listener.Start();
connection.Connect();
Thread.Sleep(100); // Gotta wait for the server to set up the events.
listener.Dispose();
Thread.Sleep(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(clientDisconnected);
Assert.IsFalse(serverDisconnected);
}
}
[TestMethod]
public void ClientDisposeDisconnectTest()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);
bool serverConnected = false;
bool serverDisconnected = false;
bool clientDisconnected = false;
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(ep, new TestLogger()))
{
listener.NewConnection += (evt) =>
{
serverConnected = true;
evt.Connection.Disconnected += (o, et) => serverDisconnected = true;
};
connection.Disconnected += (o, et) => clientDisconnected = true;
listener.Start();
connection.Connect();
Thread.Sleep(100); // Gotta wait for the server to set up the events.
connection.Dispose();
Thread.Sleep(100);
Assert.IsTrue(serverConnected);
Assert.IsTrue(serverDisconnected);
Assert.IsFalse(clientDisconnected);
}
}
/// <summary>
/// Tests the fields on UdpConnection.
/// </summary>
[TestMethod]
public void DtlsFieldTest()
{
IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(ep, new TestLogger()))
{
listener.Start();
connection.Connect();
//Connection fields
Assert.AreEqual(ep, connection.EndPoint);
//UdpConnection fields
Assert.AreEqual(new IPEndPoint(IPAddress.Loopback, 4296), connection.EndPoint);
Assert.AreEqual(1, connection.Statistics.DataBytesSent);
Assert.AreEqual(0, connection.Statistics.DataBytesReceived);
}
}
[TestMethod]
public void DtlsHandshakeTest()
{
byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
listener.Start();
MessageReader output = null;
listener.NewConnection += delegate (NewConnectionEventArgs e)
{
output = e.HandshakeData.Duplicate();
};
connection.Connect(TestData);
Thread.Sleep(10);
for (int i = 0; i < TestData.Length; ++i)
{
Assert.AreEqual(TestData[i], output.ReadByte());
}
}
}
[TestMethod]
public void DtlsUnreliableMessageSendTest()
{
byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
MessageReader output = null;
listener.NewConnection += delegate (NewConnectionEventArgs e)
{
e.Connection.DataReceived += delegate (DataReceivedEventArgs evt)
{
output = evt.Message.Duplicate();
};
};
listener.Start();
connection.Connect();
for (int i = 0; i < 4; ++i)
{
var msg = MessageWriter.Get(SendOption.None);
msg.Write(TestData);
connection.Send(msg);
msg.Recycle();
}
Thread.Sleep(10);
for (int i = 0; i < TestData.Length; ++i)
{
Assert.AreEqual(TestData[i], output.ReadByte());
}
}
}
/// <summary>
/// Tests IPv4 connectivity.
/// </summary>
[TestMethod]
public void DtlsIPv4ConnectionTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
listener.Start();
connection.Connect();
Assert.AreEqual(ConnectionState.Connected, connection.State);
}
}
[TestMethod]
public void DtlsSessionV0ConnectionTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (DtlsUnityConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
connection.HazelSessionVersion = 0;
listener.Start();
connection.Connect();
Assert.AreEqual(ConnectionState.Connected, connection.State);
}
}
private class MultipleClientHelloDtlsConnection : DtlsUnityConnection
{
public MultipleClientHelloDtlsConnection(ILogger logger, IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base(logger, remoteEndPoint, ipMode)
{
}
protected override void SendClientHello(bool isRetransmit)
{
base.SendClientHello(isRetransmit);
base.SendClientHello(true);
}
}
private class MultipleClientKeyExchangeFlightDtlsConnection : DtlsUnityConnection
{
public MultipleClientKeyExchangeFlightDtlsConnection(ILogger logger, IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base(logger, remoteEndPoint, ipMode)
{
}
protected override void SendClientKeyExchangeFlight(bool isRetransmit)
{
base.SendClientKeyExchangeFlight(isRetransmit);
base.SendClientKeyExchangeFlight(true);
base.SendClientKeyExchangeFlight(true);
}
}
/// <summary>
/// Tests IPv4 resilience to multiple hellos.
/// </summary>
[TestMethod]
public void ConnectLikeAJerkTest()
{
using (DtlsConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger("Server")))
using (MultipleClientHelloDtlsConnection client = new MultipleClientHelloDtlsConnection(new TestLogger("Client "), new IPEndPoint(IPAddress.Loopback, 4296), IPMode.IPv4))
{
client.SetValidServerCertificates(GetCertificateForClient());
int connects = 0;
listener.NewConnection += (obj) =>
{
Interlocked.Increment(ref connects);
};
listener.Start();
client.Connect(null, 1000);
Thread.Sleep(2000);
Assert.AreEqual(0, listener.ReceiveQueueLength);
Assert.IsTrue(connects <= 1, $"Too many connections: {connects}");
Assert.AreEqual(ConnectionState.Connected, client.State);
Assert.IsTrue(client.HandshakeComplete);
}
}
/// <summary>
/// Tests IPv4 resilience to multiple ClientKeyExchange packets.
/// </summary>
[TestMethod]
public void HandshakeLikeAJerkTest()
{
using (DtlsConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger("Server")))
using (MultipleClientKeyExchangeFlightDtlsConnection client = new MultipleClientKeyExchangeFlightDtlsConnection(new TestLogger("Client "), new IPEndPoint(IPAddress.Loopback, 4296), IPMode.IPv4))
{
client.SetValidServerCertificates(GetCertificateForClient());
int connects = 0;
listener.NewConnection += (obj) =>
{
Interlocked.Increment(ref connects);
};
listener.Start();
client.Connect();
Thread.Sleep(500);
Assert.AreEqual(0, listener.ReceiveQueueLength);
Assert.IsTrue(connects <= 1, $"Too many connections: {connects}");
Assert.AreEqual(ConnectionState.Connected, client.State);
Assert.IsTrue(client.HandshakeComplete);
}
}
/// <summary>
/// Tests dual mode connectivity.
/// </summary>
[TestMethod]
public void MixedConnectionTest()
{
using (ThreadLimitedUdpConnectionListener listener2 = this.CreateListener(4, new IPEndPoint(IPAddress.IPv6Any, 4296), new TestLogger(), IPMode.IPv6))
{
listener2.Start();
listener2.NewConnection += (evt) =>
{
Console.WriteLine($"Connection: {evt.Connection.EndPoint}");
};
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), new TestLogger()))
{
connection.Connect();
Assert.AreEqual(ConnectionState.Connected, connection.State);
}
using (UdpConnection connection2 = this.CreateConnection(new IPEndPoint(IPAddress.IPv6Loopback, 4296), new TestLogger(), IPMode.IPv6))
{
connection2.Connect();
Assert.AreEqual(ConnectionState.Connected, connection2.State);
}
}
}
/// <summary>
/// Tests dual mode connectivity.
/// </summary>
[TestMethod]
public void DtlsIPv6ConnectionTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.IPv6Any, 4296), new TestLogger(), IPMode.IPv6))
{
listener.Start();
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), new TestLogger(), IPMode.IPv6))
{
connection.Connect();
}
}
}
/// <summary>
/// Tests server to client unreliable communication on the UdpConnection.
/// </summary>
[TestMethod]
public void DtlsUnreliableServerToClientTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
TestHelper.RunServerToClientTest(listener, connection, 10, SendOption.None);
}
}
/// <summary>
/// Tests server to client reliable communication on the UdpConnection.
/// </summary>
[TestMethod]
public void DtlsReliableServerToClientTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
TestHelper.RunServerToClientTest(listener, connection, 10, SendOption.Reliable);
}
}
/// <summary>
/// Tests server to client unreliable communication on the UdpConnection.
/// </summary>
[TestMethod]
public void DtlsUnreliableClientToServerTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
TestHelper.RunClientToServerTest(listener, connection, 10, SendOption.None);
}
}
/// <summary>
/// Tests server to client reliable communication on the UdpConnection.
/// </summary>
[TestMethod]
public void DtlsReliableClientToServerTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
TestHelper.RunClientToServerTest(listener, connection, 10, SendOption.Reliable);
}
}
[TestMethod]
public void KeepAliveClientTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
listener.Start();
connection.Connect();
connection.KeepAliveInterval = 100;
Thread.Sleep(1050); //Enough time for ~10 keep alive packets
Assert.AreEqual(ConnectionState.Connected, connection.State);
Assert.IsTrue(
connection.Statistics.TotalBytesSent >= 500 &&
connection.Statistics.TotalBytesSent <= 675,
"Sent: " + connection.Statistics.TotalBytesSent
);
}
}
/// <summary>
/// Tests the keepalive functionality from the client,
/// </summary>
[TestMethod]
public void KeepAliveServerTest()
{
ManualResetEvent mutex = new ManualResetEvent(false);
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
UdpConnection client = null;
listener.NewConnection += delegate (NewConnectionEventArgs args)
{
client = (UdpConnection)args.Connection;
client.KeepAliveInterval = 100;
Thread timeoutThread = new Thread(() =>
{
Thread.Sleep(1050); //Enough time for ~10 keep alive packets
mutex.Set();
});
timeoutThread.Start();
};
listener.Start();
connection.Connect();
mutex.WaitOne();
Assert.AreEqual(ConnectionState.Connected, client.State);
Assert.IsTrue(
client.Statistics.TotalBytesSent >= 27 &&
client.Statistics.TotalBytesSent <= 50,
"Sent: " + client.Statistics.TotalBytesSent
);
}
}
/// <summary>
/// Tests disconnection from the client.
/// </summary>
[TestMethod]
public void ClientDisconnectTest()
{
using (var listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger("Server")))
using (var connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger("Client")))
{
ManualResetEvent mutex = new ManualResetEvent(false);
ManualResetEvent mutex2 = new ManualResetEvent(false);
listener.NewConnection += delegate (NewConnectionEventArgs args)
{
args.Connection.Disconnected += delegate (object sender2, DisconnectedEventArgs args2)
{
mutex2.Set();
};
mutex.Set();
};
listener.Start();
connection.Connect();
Assert.AreEqual(ConnectionState.Connected, connection.State);
mutex.WaitOne(1000);
Assert.AreEqual(ConnectionState.Connected, connection.State);
connection.Disconnect("Testing");
mutex2.WaitOne(1000);
Assert.AreEqual(ConnectionState.NotConnected, connection.State);
}
}
/// <summary>
/// Tests disconnection from the server.
/// </summary>
[TestMethod]
public void ServerDisconnectTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger("Server")))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger("Client")))
{
SemaphoreSlim mutex = new SemaphoreSlim(0, 100);
ManualResetEventSlim serverMutex = new ManualResetEventSlim(false);
connection.Disconnected += delegate (object sender, DisconnectedEventArgs args)
{
mutex.Release();
};
listener.NewConnection += delegate (NewConnectionEventArgs args)
{
mutex.Release();
// This has to be on a new thread because the client will go straight from Connecting to NotConnected
ThreadPool.QueueUserWorkItem(_ =>
{
serverMutex.Wait(500);
args.Connection.Disconnect("Testing");
});
};
listener.Start();
connection.Connect();
mutex.Wait(500);
Assert.AreEqual(ConnectionState.Connected, connection.State);
serverMutex.Set();
mutex.Wait(500);
Assert.AreEqual(ConnectionState.NotConnected, connection.State);
}
}
/// <summary>
/// Tests disconnection from the server.
/// </summary>
[TestMethod]
public void ServerExtraDataDisconnectTest()
{
using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
{
string received = null;
ManualResetEvent mutex = new ManualResetEvent(false);
connection.Disconnected += delegate (object sender, DisconnectedEventArgs args)
{
// We don't own the message, we have to read the string now
received = args.Message.ReadString();
mutex.Set();
};
listener.NewConnection += delegate (NewConnectionEventArgs args)
{
MessageWriter writer = MessageWriter.Get(SendOption.None);
writer.Write("Goodbye");
args.Connection.Disconnect("Testing", writer);
};
listener.Start();
connection.Connect();
mutex.WaitOne(5000);
Assert.IsNotNull(received);
Assert.AreEqual("Goodbye", received);
}
}
}
}
|