forked from bmjoy/BenchmarkNet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BenchmarkNet.cs
1948 lines (1590 loc) · 70.5 KB
/
BenchmarkNet.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
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
/*
* BenchmarkNet is a console application for testing the reliable UDP networking solutions
* Copyright (c) 2018 Stanislav Denisov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.IO.Pipes;
using System.Net;
using System.Reflection;
using System.Runtime;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
// ENet 2.0.8 (https://github.com/nxrighthere/ENet-CSharp)
using ENet;
// UNet 1.0.0.9 (https://forum.unity.com/threads/standalone-library-binaries-aka-server-dll.526718)
using UnetServerDll;
// LiteNetLib 0.8 (https://github.com/RevenantX/LiteNetLib)
using LiteNetLib;
using LiteNetLib.Utils;
// Lidgren 1.7.0 (https://github.com/lidgren/lidgren-network-gen3)
using Lidgren.Network;
// MiniUDP 0.8.5 (https://github.com/ashoulson/MiniUDP)
using MiniUDP;
// Hazel 0.1.2 (https://github.com/DarkRiftNetworking/Hazel-Networking)
using Hazel;
using Hazel.Udp;
// Photon 4.0.29 (https://www.photonengine.com/en/OnPremise)
using ExitGames.Client.Photon;
// Neutrino 1.0 (https://github.com/Claytonious/Neutrino)
using Neutrino.Core;
using Neutrino.Core.Messages;
// DarkRift 2.2.0 (https://darkriftnetworking.com/DarkRift2)
using DarkRift;
using DarkRift.Server;
using DarkRift.Client;
namespace NX {
public abstract class BenchmarkNet {
// Meta
public const string title = "BenchmarkNet";
public const string version = "1.10";
// Parameters
public const string ip = "127.0.0.1";
public static byte selectedLibrary = 0;
public static ushort port = 0;
public static ushort maxClients = 0;
public static int serverTickRate = 0;
public static int clientTickRate = 0;
public static int sendRate = 0;
public static int reliableMessages = 0;
public static int unreliableMessages = 0;
public static string message = String.Empty;
// Status
public static volatile bool processActive = false;
public static volatile bool processCompleted = false;
public static volatile bool processCrashed = false;
public static volatile bool processFailure = false;
public static volatile bool processOverload = false;
public static volatile bool processUninitialized = true;
// Stats
public static volatile int serverReliableSent = 0;
public static volatile int serverReliableReceived = 0;
public static volatile int serverReliableBytesSent = 0;
public static volatile int serverReliableBytesReceived = 0;
public static volatile int serverUnreliableSent = 0;
public static volatile int serverUnreliableReceived = 0;
public static volatile int serverUnreliableBytesSent = 0;
public static volatile int serverUnreliableBytesReceived = 0;
public static volatile int clientsStartedCount = 0;
public static volatile int clientsConnectedCount = 0;
public static volatile int clientsStreamsCount = 0;
public static volatile int clientsDisconnectedCount = 0;
public static volatile int clientsReliableSent = 0;
public static volatile int clientsReliableReceived = 0;
public static volatile int clientsReliableBytesSent = 0;
public static volatile int clientsReliableBytesReceived = 0;
public static volatile int clientsUnreliableSent = 0;
public static volatile int clientsUnreliableReceived = 0;
public static volatile int clientsUnreliableBytesSent = 0;
public static volatile int clientsUnreliableBytesReceived = 0;
// Libraries
public static readonly string[] networkingLibraries = {
"ENet",
"UNet",
"LiteNetLib",
"Lidgren",
"MiniUDP",
"Hazel",
"Photon",
"Neutrino",
"DarkRift"
};
// Data
protected static byte[] messageData;
protected static byte[] reversedData;
protected static char[] reversedMessage;
// Internals
private static bool serverInstance = false;
private static bool clientsInstance = false;
private static bool maxClientsPass = true;
private static bool sustainedLowLatency = false;
private static ushort maxPeers = 0;
private static BinaryFormatter binaryFormatter;
private static ServerMessage serverMessage;
private static ClientsMessage clientsMessage;
private static MemoryMappedViewStream serverStream;
private static MemoryMappedViewStream clientsStream;
private static NamedPipeServerStream serverPipe;
private static NamedPipeServerStream clientsPipe;
private static Process serverProcess;
private static Process clientsProcess;
private static Thread serverThread;
private const int memoryMappedLength = 512;
private const ushort defaultPort = 9500;
private const ushort defaultMaxClients = 1000;
private const int defaultServerTickRate = 64;
private const int defaultClientTickRate = 64;
private const int defaultSendRate = 15;
private const int defaultReliableMessages = 500;
private const int defaultUnreliableMessages = 1000;
private const string defaultMessage = "Sometimes we just need a good networking library";
// Functions
#if !GUI
private static readonly Func<int, string> Space = (value) => String.Empty.PadRight(value);
private static readonly Func<int, decimal, decimal, decimal> PayloadThroughput = (clientsStreamsCount, messageLength, sendRate) => (clientsStreamsCount * (messageLength * sendRate * 2) * 8 / (1000 * 1000));
#else
#endif
[Serializable]
private struct ServerMessage {
public bool uninitialized;
public int reliableSent;
public int reliableReceived;
public int reliableBytesSent;
public int reliableBytesReceived;
public int unreliableSent;
public int unreliableReceived;
public int unreliableBytesSent;
public int unreliableBytesReceived;
}
[Serializable]
private struct ClientsMessage {
public int startedCount;
public int connectedCount;
public int streamsCount;
public int disconnectedCount;
public int reliableSent;
public int reliableReceived;
public int reliableBytesSent;
public int reliableBytesReceived;
public int unreliableSent;
public int unreliableReceived;
public int unreliableBytesSent;
public int unreliableBytesReceived;
}
public static bool Initialize() {
binaryFormatter = new BinaryFormatter();
MemoryMappedFile serverData = MemoryMappedFile.CreateOrOpen(title + "ServerData", memoryMappedLength, MemoryMappedFileAccess.ReadWrite);
serverStream = serverData.CreateViewStream(0, memoryMappedLength);
binaryFormatter.Serialize(serverStream, serverMessage);
serverStream.Position = 0;
MemoryMappedFile clientsData = MemoryMappedFile.CreateOrOpen(title + "ClientsData", memoryMappedLength, MemoryMappedFileAccess.ReadWrite);
clientsStream = clientsData.CreateViewStream(0, memoryMappedLength);
binaryFormatter.Serialize(clientsStream, clientsMessage);
clientsStream.Position = 0;
if (serverInstance) {
if (selectedLibrary == 0)
serverThread = new Thread(ENetBenchmark.Server);
else if (selectedLibrary == 1)
serverThread = new Thread(UNetBenchmark.Server);
else if (selectedLibrary == 2)
serverThread = new Thread(LiteNetLibBenchmark.Server);
else if (selectedLibrary == 3)
serverThread = new Thread(LidgrenBenchmark.Server);
else if (selectedLibrary == 4)
serverThread = new Thread(MiniUDPBenchmark.Server);
else if (selectedLibrary == 5)
serverThread = new Thread(HazelBenchmark.Server);
else if (selectedLibrary == 6)
serverThread = new Thread(PhotonBenchmark.Server);
else if (selectedLibrary == 7)
serverThread = new Thread(NeutrinoBenchmark.Server);
else if (selectedLibrary == 8)
serverThread = new Thread(DarkRiftBenchmark.Server);
if (serverThread == null)
return false;
}
UInt16.TryParse(ConfigurationManager.AppSettings["Port"], out port);
Int32.TryParse(ConfigurationManager.AppSettings["ServerTickRate"], out serverTickRate);
Int32.TryParse(ConfigurationManager.AppSettings["ClientTickRate"], out clientTickRate);
Int32.TryParse(ConfigurationManager.AppSettings["SendRate"], out sendRate);
Int32.TryParse(ConfigurationManager.AppSettings["ReliableMessages"], out reliableMessages);
Int32.TryParse(ConfigurationManager.AppSettings["UnreliableMessages"], out unreliableMessages);
message = ConfigurationManager.AppSettings["Message"];
Boolean.TryParse(ConfigurationManager.AppSettings["SustainedLowLatency"], out sustainedLowLatency);
if (port == 0)
port = defaultPort;
if (maxClients == 0)
maxClients = defaultMaxClients;
if (serverTickRate == 0)
serverTickRate = defaultServerTickRate;
if (clientTickRate == 0)
clientTickRate = defaultClientTickRate;
if (sendRate == 0)
sendRate = defaultSendRate;
if (reliableMessages == 0)
reliableMessages = defaultReliableMessages;
if (unreliableMessages == 0)
unreliableMessages = defaultUnreliableMessages;
if (message.Length == 0)
message = defaultMessage;
reversedMessage = message.ToCharArray();
Array.Reverse(reversedMessage);
messageData = Encoding.ASCII.GetBytes(message);
reversedData = Encoding.ASCII.GetBytes(new string(reversedMessage));
#if !GUI
Console.CursorVisible = false;
Console.Clear();
#endif
processActive = true;
if (serverInstance || clientsInstance) {
if (selectedLibrary == Array.FindIndex(networkingLibraries, entry => entry.Contains("ENet")))
ENet.Library.Initialize();
}
if (serverInstance) {
if (sustainedLowLatency)
GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
maxPeers = ushort.MaxValue - 1;
maxClientsPass = (selectedLibrary > 0 ? maxClients <= maxPeers : maxClients <= ENet.Library.maxPeers);
if (!maxClientsPass)
maxClients = Math.Min(Math.Max((ushort)1, (ushort)maxClients), (selectedLibrary > 0 ? maxPeers : (ushort)ENet.Library.maxPeers));
serverThread.Priority = ThreadPriority.AboveNormal;
serverThread.Start();
Thread.Sleep(100);
}
if (!serverInstance && !clientsInstance) {
serverProcess = Process.Start(new ProcessStartInfo {
FileName = Assembly.GetExecutingAssembly().Location,
Arguments = "-library:" + selectedLibrary + " -server:" + maxClients,
CreateNoWindow = true,
UseShellExecute = false
});
clientsProcess = Process.Start(new ProcessStartInfo {
FileName = Assembly.GetExecutingAssembly().Location,
Arguments = "-library:" + selectedLibrary + " -clients:" + maxClients,
CreateNoWindow = true,
UseShellExecute = false
});
}
Task pulseTask = Pulse();
Task dataTask = serverInstance && selectedLibrary == Array.FindIndex(networkingLibraries, entry => entry.Contains("Photon")) ? null : Data();
#if !GUI
Task infoTask = serverInstance || clientsInstance ? null : Info();
#endif
Task superviseTask = serverInstance || clientsInstance ? null : Supervise();
Task spawnTask = serverInstance || !clientsInstance ? null : Spawn();
if (serverInstance)
processUninitialized = false;
return true;
}
private static void Deinitialize() {
processActive = false;
if (!serverProcess.HasExited)
serverProcess.Kill();
if (!clientsProcess.HasExited)
clientsProcess.Kill();
}
[STAThread]
private static void Main(string[] arguments) {
for (int i = 0; i < arguments.Length; i++) {
string argument = arguments[i].ToLower();
if (argument.Contains("-library"))
Byte.TryParse(argument.Substring(argument.LastIndexOf(":") + 1), out selectedLibrary);
if (argument.Contains("-server")) {
serverInstance = true;
UInt16.TryParse(argument.Substring(argument.LastIndexOf(":") + 1), out maxClients);
}
if (argument.Contains("-clients")) {
clientsInstance = true;
UInt16.TryParse(argument.Substring(argument.LastIndexOf(":") + 1), out maxClients);
}
}
#if GUI
#else
Console.Title = title;
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192), Console.InputEncoding, false, bufferSize: 1024));
Start:
if (!serverInstance && !clientsInstance) {
Console.WriteLine("Welcome to " + title + Space(1) + version + "!");
Console.WriteLine(Environment.NewLine + "Source code is available on GitHub (https://github.com/nxrighthere/BenchmarkNet)");
Console.WriteLine("If you have any questions, contact me ([email protected])");
if (sustainedLowLatency) {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(Environment.NewLine + "The server process will perform in Sustained Low Latency mode.");
Console.ResetColor();
}
Console.WriteLine(Environment.NewLine + "Select the networking library:");
for (int i = 0; i < networkingLibraries.Length; i++) {
Console.WriteLine("(" + i + ") " + networkingLibraries[i]);
}
Console.Write(Environment.NewLine + "Enter the number (default 0): ");
Byte.TryParse(Console.ReadLine(), out selectedLibrary);
if (selectedLibrary >= networkingLibraries.Length) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Please, enter a valid number of the networking library!");
Console.ResetColor();
Console.ReadKey();
Console.Clear();
goto Start;
}
Console.Write("Simulated clients (default " + defaultMaxClients + "): ");
UInt16.TryParse(Console.ReadLine(), out maxClients);
}
if (!Initialize()) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Initialization failed!");
}
Console.ReadKey();
#endif
Deinitialize();
Environment.Exit(0);
}
private static async Task Pulse() {
await Task.Factory.StartNew(() => {
const string serverPipeName = title + "Server";
const string clientsPipeName = title + "Clients";
if (serverInstance) {
NamedPipeClientStream serverPipeStream = new NamedPipeClientStream(".", serverPipeName, PipeDirection.In);
serverPipeStream.Connect();
serverPipeStream.BeginRead(new byte[1], 0, 1, (result) => Process.GetCurrentProcess().Kill(), serverPipeStream);
} else if (clientsInstance) {
NamedPipeClientStream clientsPipeStream = new NamedPipeClientStream(".", clientsPipeName, PipeDirection.In);
clientsPipeStream.Connect();
clientsPipeStream.BeginRead(new byte[1], 0, 1, (result) => Process.GetCurrentProcess().Kill(), clientsPipeStream);
} else {
Task.Run(async() => {
serverPipe = new NamedPipeServerStream(serverPipeName, PipeDirection.Out);
await serverPipe.WaitForConnectionAsync();
});
Task.Run(async() => {
clientsPipe = new NamedPipeServerStream(clientsPipeName, PipeDirection.Out);
await clientsPipe.WaitForConnectionAsync();
});
}
}, TaskCreationOptions.LongRunning);
}
private static async Task Data() {
await Task.Factory.StartNew(() => {
bool monitoringInstance = !serverInstance && !clientsInstance;
byte[] serverBuffer = !monitoringInstance ? null : new byte[memoryMappedLength];
byte[] clientsBuffer = !monitoringInstance ? null : new byte[memoryMappedLength];
MemoryStream serverMemory = !monitoringInstance ? null : new MemoryStream(serverBuffer);
MemoryStream clientsMemory = !monitoringInstance ? null : new MemoryStream(clientsBuffer);
while (processActive) {
if (serverInstance) {
serverMessage.uninitialized = processUninitialized;
serverMessage.reliableSent = serverReliableSent;
serverMessage.reliableReceived = serverReliableReceived;
serverMessage.reliableBytesSent = serverReliableBytesSent;
serverMessage.reliableBytesReceived = serverReliableBytesReceived;
serverMessage.unreliableSent = serverUnreliableSent;
serverMessage.unreliableReceived = serverUnreliableReceived;
serverMessage.unreliableBytesSent = serverUnreliableBytesSent;
serverMessage.unreliableBytesReceived = serverUnreliableBytesReceived;
binaryFormatter.Serialize(serverStream, serverMessage);
serverStream.Position = 0;
} else if (clientsInstance) {
clientsMessage.startedCount = clientsStartedCount;
clientsMessage.connectedCount = clientsConnectedCount;
clientsMessage.streamsCount = clientsStreamsCount;
clientsMessage.disconnectedCount = clientsDisconnectedCount;
clientsMessage.reliableSent = clientsReliableSent;
clientsMessage.reliableReceived = clientsReliableReceived;
clientsMessage.reliableBytesSent = clientsReliableBytesSent;
clientsMessage.reliableBytesReceived = clientsReliableBytesReceived;
clientsMessage.unreliableSent = clientsUnreliableSent;
clientsMessage.unreliableReceived = clientsUnreliableReceived;
clientsMessage.unreliableBytesSent = clientsUnreliableBytesSent;
clientsMessage.unreliableBytesReceived = clientsUnreliableBytesReceived;
binaryFormatter.Serialize(clientsStream, clientsMessage);
clientsStream.Position = 0;
} else {
serverStream.Read(serverBuffer, 0, memoryMappedLength);
clientsStream.Read(clientsBuffer, 0, memoryMappedLength);
serverMessage = (ServerMessage)binaryFormatter.Deserialize(serverMemory);
processUninitialized = serverMessage.uninitialized;
serverReliableSent = serverMessage.reliableSent;
serverReliableReceived = serverMessage.reliableReceived;
serverReliableBytesSent = serverMessage.reliableBytesSent;
serverReliableBytesReceived = serverMessage.reliableBytesReceived;
serverUnreliableSent = serverMessage.unreliableSent;
serverUnreliableReceived = serverMessage.unreliableReceived;
serverUnreliableBytesSent = serverMessage.unreliableBytesSent;
serverUnreliableBytesReceived = serverMessage.unreliableBytesReceived;
serverMemory.Position = 0;
clientsMessage = (ClientsMessage)binaryFormatter.Deserialize(clientsMemory);
clientsStartedCount = clientsMessage.startedCount;
clientsConnectedCount = clientsMessage.connectedCount;
clientsStreamsCount = clientsMessage.streamsCount;
clientsDisconnectedCount = clientsMessage.disconnectedCount;
clientsReliableSent = clientsMessage.reliableSent;
clientsReliableReceived = clientsMessage.reliableReceived;
clientsReliableBytesSent = clientsMessage.reliableBytesSent;
clientsReliableBytesReceived = clientsMessage.reliableBytesReceived;
clientsUnreliableSent = clientsMessage.unreliableSent;
clientsUnreliableReceived = clientsMessage.unreliableReceived;
clientsUnreliableBytesSent = clientsMessage.unreliableBytesSent;
clientsUnreliableBytesReceived = clientsMessage.unreliableBytesReceived;
clientsMemory.Position = 0;
serverStream.Position = 0;
clientsStream.Position = 0;
}
Thread.Sleep(15);
}
}, TaskCreationOptions.LongRunning);
}
#if !GUI
private static async Task Info() {
await Task.Factory.StartNew(() => {
int spinnerTimer = 0;
int spinnerSequence = 0;
string space = Space(10);
string[] spinner = {
"/",
"—",
"\\",
"|"
};
string[] status = {
"Running" + Space(6),
"Crashed" + Space(6),
"Failure" + Space(6),
"Overload" + Space(5),
"Completed" + Space(4),
"Uninitialized"
};
string[] strings = {
"Benchmarking " + networkingLibraries[selectedLibrary] + "...",
"Server tick rate: " + serverTickRate + ", Client tick rate: " + clientTickRate + " (ticks per second)",
maxClients + " clients, " + reliableMessages + " reliable and " + unreliableMessages + " unreliable messages per client, " + sendRate + " messages per second, " + messageData.Length + " bytes per message",
"GC mode: " + (!GCSettings.IsServerGC ? "Workstation" : "Server"),
"This networking library doesn't support more than " + (selectedLibrary > 0 ? maxPeers : ENet.Library.maxPeers).ToString() + " peers per server!",
"The server process is performing in Sustained Low Latency mode.",
};
for (int i = 0; i < spinner.Length; i++) {
spinner[i] = Environment.NewLine + "Press any key to stop the process" + Space(1) + spinner[i];
}
Console.WriteLine(strings[0]);
Console.WriteLine(strings[1]);
Console.WriteLine(strings[2]);
Console.WriteLine(strings[3]);
StringBuilder info = new StringBuilder(1024);
Stopwatch elapsedTime = Stopwatch.StartNew();
while (processActive) {
Console.CursorVisible = false;
Console.SetCursorPosition(0, 4);
if (!maxClientsPass || sustainedLowLatency)
Console.WriteLine();
if (!maxClientsPass) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(strings[4]);
Console.ResetColor();
}
if (sustainedLowLatency) {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(strings[5]);
Console.ResetColor();
}
info.Clear()
.AppendLine().Append("[Server]")
.AppendLine().Append("Status: ").Append(processCrashed ? status[1] : (processFailure ? status[2] : (processOverload ? status[3] : (processCompleted ? status[4] : (processUninitialized ? status[5] : status[0])))))
.AppendLine().Append("Sent -> Reliable: ").Append(serverReliableSent).Append(" messages (").Append(serverReliableBytesSent).Append(" bytes), Unreliable: ").Append(serverUnreliableSent).Append(" messages (").Append(serverUnreliableBytesSent).Append(" bytes)")
.AppendLine().Append("Received <- Reliable: ").Append(serverReliableReceived).Append(" messages (").Append(serverReliableBytesReceived).Append(" bytes), Unreliable: ").Append(serverUnreliableReceived).Append(" messages (").Append(serverUnreliableBytesReceived).Append(" bytes)")
.AppendLine().Append("Payload throughput: ").Append(PayloadThroughput(clientsStreamsCount, messageData.Length, sendRate).ToString("0.00")).Append(" mbps \\ ").Append(PayloadThroughput(maxClients * 2, messageData.Length, sendRate).ToString("0.00")).Append(" mbps").Append(space)
.AppendLine()
.AppendLine().Append("[Clients]")
.AppendLine().Append("Status: ").Append(clientsStartedCount).Append(" started, ").Append(clientsConnectedCount).Append(" connected, ").Append(clientsDisconnectedCount).Append(" dropped")
.AppendLine().Append("Sent -> Reliable: ").Append(clientsReliableSent).Append(" messages (").Append(clientsReliableBytesSent).Append(" bytes), Unreliable: ").Append(clientsUnreliableSent).Append(" messages (").Append(clientsUnreliableBytesSent).Append(" bytes)")
.AppendLine().Append("Received <- Reliable: ").Append(clientsReliableReceived).Append(" messages (").Append(clientsReliableBytesReceived).Append(" bytes), Unreliable: ").Append(clientsUnreliableReceived).Append(" messages (").Append(clientsUnreliableBytesReceived).Append(" bytes)")
.AppendLine()
.AppendLine().Append("[Summary]")
.AppendLine().Append("Total - Reliable: ").Append((ulong)clientsReliableSent + (ulong)serverReliableReceived + (ulong)serverReliableSent + (ulong)clientsReliableReceived).Append(" messages (").Append((ulong)clientsReliableBytesSent + (ulong)serverReliableBytesReceived + (ulong)serverReliableBytesSent + (ulong)clientsReliableBytesReceived).Append(" bytes), Unreliable: ").Append((ulong)clientsUnreliableSent + (ulong)serverUnreliableReceived + (ulong)serverUnreliableSent + (ulong)clientsUnreliableReceived).Append(" messages (").Append((ulong)clientsUnreliableBytesSent + (ulong)serverUnreliableBytesReceived + (ulong)serverUnreliableBytesSent + (ulong)clientsUnreliableBytesReceived).Append(" bytes)")
.AppendLine().Append("Expected - Reliable: ").Append(maxClients * (ulong)reliableMessages * 4).Append(" messages (").Append(maxClients * (ulong)reliableMessages * (ulong)messageData.Length * 4).Append(" bytes), Unreliable: ").Append(maxClients * (ulong)unreliableMessages * 4).Append(" messages (").Append(maxClients * (ulong)unreliableMessages * (ulong)messageData.Length * 4).Append(" bytes)")
.AppendLine().Append("Elapsed time: ").Append(elapsedTime.Elapsed.Hours.ToString("00")).Append(":").Append(elapsedTime.Elapsed.Minutes.ToString("00")).Append(":").Append(elapsedTime.Elapsed.Seconds.ToString("00"));
Console.WriteLine(info);
if (spinnerTimer >= 10) {
spinnerSequence++;
spinnerTimer = 0;
if (spinnerSequence == spinner.Length)
spinnerSequence = 0;
} else {
spinnerTimer++;
}
Console.WriteLine(spinner[spinnerSequence]);
Thread.Sleep(1000 / 60);
}
elapsedTime.Stop();
if (!processActive && processCompleted) {
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine("Process completed! Press any key to exit...");
}
}, TaskCreationOptions.LongRunning);
}
#endif
private static async Task Supervise() {
await Task.Factory.StartNew(() => {
decimal currentData = 0;
decimal lastData = 0;
bool recollectData = true;
while (processActive) {
Thread.Sleep(1000);
Collect:
currentData = ((decimal)serverReliableSent + (decimal)serverReliableReceived + (decimal)serverUnreliableSent + (decimal)serverUnreliableReceived + (decimal)clientsReliableSent + (decimal)clientsReliableReceived + (decimal)clientsUnreliableSent + (decimal)clientsUnreliableReceived);
if (serverProcess.HasExited)
processCrashed = true;
if (currentData == lastData) {
if (currentData == 0) {
if (recollectData) {
recollectData = false;
Thread.Sleep(4000);
goto Collect;
}
processFailure = true;
} else if (clientsDisconnectedCount > 1 || ((currentData / (maxClients * ((decimal)reliableMessages + (decimal)unreliableMessages) * 4)) * 100) < 90) {
processOverload = true;
}
processCompleted = true;
Thread.Sleep(100);
Deinitialize();
break;
}
lastData = currentData;
}
if (serverInstance || clientsInstance) {
if (selectedLibrary == Array.FindIndex(networkingLibraries, entry => entry.Contains("ENet")))
ENet.Library.Deinitialize();
}
}, TaskCreationOptions.LongRunning);
}
private static async Task Spawn() {
await Task.Factory.StartNew(() => {
Task[] clients = new Task[maxClients];
for (int i = 0; i < maxClients; i++) {
if (!processActive)
break;
if (selectedLibrary == 0)
clients[i] = ENetBenchmark.Client();
else if (selectedLibrary == 1)
clients[i] = UNetBenchmark.Client();
else if (selectedLibrary == 2)
clients[i] = LiteNetLibBenchmark.Client();
else if (selectedLibrary == 3)
clients[i] = LidgrenBenchmark.Client();
else if (selectedLibrary == 4)
clients[i] = MiniUDPBenchmark.Client();
else if (selectedLibrary == 5)
clients[i] = HazelBenchmark.Client();
else if (selectedLibrary == 6)
clients[i] = PhotonBenchmark.Client();
else if (selectedLibrary == 7)
clients[i] = NeutrinoBenchmark.Client();
else if (selectedLibrary == 8)
clients[i] = DarkRiftBenchmark.Client();
Interlocked.Increment(ref clientsStartedCount);
Thread.Sleep(15);
}
}, TaskCreationOptions.LongRunning);
}
}
public sealed class ENetBenchmark : BenchmarkNet {
private static void SendReliable(byte[] data, byte channelID, Peer peer) {
Packet packet = default(Packet);
packet.Create(data, data.Length, PacketFlags.Reliable | PacketFlags.NoAllocate); // Reliable Sequenced
peer.Send(channelID, ref packet);
}
private static void SendUnreliable(byte[] data, byte channelID, Peer peer) {
Packet packet = default(Packet);
packet.Create(data, data.Length, PacketFlags.None | PacketFlags.NoAllocate); // Unreliable Sequenced
peer.Send(channelID, ref packet);
}
public static void Server() {
using (Host server = new Host()) {
Address address = new Address();
address.Port = port;
server.Create(address, maxClients, 4);
while (processActive) {
server.Service(1000 / serverTickRate, out Event netEvent);
switch (netEvent.Type) {
case EventType.None:
break;
case EventType.Receive:
if (netEvent.ChannelID == 2) {
Interlocked.Increment(ref serverReliableReceived);
Interlocked.Add(ref serverReliableBytesReceived, netEvent.Packet.Length);
SendReliable(messageData, 0, netEvent.Peer);
Interlocked.Increment(ref serverReliableSent);
Interlocked.Add(ref serverReliableBytesSent, messageData.Length);
} else if (netEvent.ChannelID == 3) {
Interlocked.Increment(ref serverUnreliableReceived);
Interlocked.Add(ref serverUnreliableBytesReceived, netEvent.Packet.Length);
SendUnreliable(reversedData, 1, netEvent.Peer);
Interlocked.Increment(ref serverUnreliableSent);
Interlocked.Add(ref serverUnreliableBytesSent, reversedData.Length);
}
netEvent.Packet.Dispose();
break;
}
}
}
}
public static async Task Client() {
await Task.Factory.StartNew(() => {
using (Host client = new Host()) {
Address address = new Address();
address.SetHost(ip);
address.Port = port;
client.Create();
Peer peer = client.Connect(address, 4);
int reliableToSend = 0;
int unreliableToSend = 0;
Task.Factory.StartNew(async() => {
bool reliableIncremented = false;
bool unreliableIncremented = false;
while (processActive) {
if (reliableToSend > 0) {
SendReliable(messageData, 2, peer);
Interlocked.Decrement(ref reliableToSend);
Interlocked.Increment(ref clientsReliableSent);
Interlocked.Add(ref clientsReliableBytesSent, messageData.Length);
}
if (unreliableToSend > 0) {
SendUnreliable(reversedData, 3, peer);
Interlocked.Decrement(ref unreliableToSend);
Interlocked.Increment(ref clientsUnreliableSent);
Interlocked.Add(ref clientsUnreliableBytesSent, reversedData.Length);
}
if (reliableToSend > 0 && !reliableIncremented) {
reliableIncremented = true;
Interlocked.Increment(ref clientsStreamsCount);
} else if (reliableToSend == 0 && reliableIncremented) {
reliableIncremented = false;
Interlocked.Decrement(ref clientsStreamsCount);
}
if (unreliableToSend > 0 && !unreliableIncremented) {
unreliableIncremented = true;
Interlocked.Increment(ref clientsStreamsCount);
} else if (unreliableToSend == 0 && unreliableIncremented) {
unreliableIncremented = false;
Interlocked.Decrement(ref clientsStreamsCount);
}
await Task.Delay(1000 / sendRate);
}
}, TaskCreationOptions.AttachedToParent);
while (processActive) {
client.Service(1000 / clientTickRate, out Event netEvent);
switch (netEvent.Type) {
case EventType.None:
break;
case EventType.Connect:
Interlocked.Increment(ref clientsConnectedCount);
Interlocked.Exchange(ref reliableToSend, reliableMessages);
Interlocked.Exchange(ref unreliableToSend, unreliableMessages);
break;
case EventType.Disconnect: case EventType.Timeout:
Interlocked.Increment(ref clientsDisconnectedCount);
Interlocked.Exchange(ref reliableToSend, 0);
Interlocked.Exchange(ref unreliableToSend, 0);
break;
case EventType.Receive:
if (netEvent.ChannelID == 0) {
Interlocked.Increment(ref clientsReliableReceived);
Interlocked.Add(ref clientsReliableBytesReceived, netEvent.Packet.Length);
} else if (netEvent.ChannelID == 1) {
Interlocked.Increment(ref clientsUnreliableReceived);
Interlocked.Add(ref clientsUnreliableBytesReceived, netEvent.Packet.Length);
}
netEvent.Packet.Dispose();
break;
}
}
peer.Disconnect(0);
}
}, TaskCreationOptions.LongRunning);
}
}
public sealed class UNetBenchmark : BenchmarkNet {
public static void Server() {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.ThreadPoolSize = 4;
globalConfig.ThreadAwakeTimeout = (uint)serverTickRate;
globalConfig.MaxHosts = 1;
globalConfig.MaxPacketSize = (ushort)((messageData.Length * 2) + 32);
globalConfig.ReactorMaximumSentMessages = (ushort)((reliableMessages + unreliableMessages) * sendRate);
globalConfig.ReactorMaximumReceivedMessages = (ushort)((reliableMessages + unreliableMessages) * sendRate);
ConnectionConfig connectionConfig = new ConnectionConfig();
int reliableChannel = connectionConfig.AddChannel(QosType.ReliableSequenced);
int unreliableChannel = connectionConfig.AddChannel(QosType.UnreliableSequenced);
connectionConfig.SendDelay = 1;
connectionConfig.MinUpdateTimeout = 1;
connectionConfig.PingTimeout = 2000;
connectionConfig.DisconnectTimeout = 5000;
connectionConfig.PacketSize = (ushort)((messageData.Length * 2) + 32);
HostTopology topology = new HostTopology(connectionConfig, maxClients);
topology.SentMessagePoolSize = (ushort)((reliableMessages + unreliableMessages) * sendRate);
topology.ReceivedMessagePoolSize = (ushort)((reliableMessages + unreliableMessages) * sendRate);
NetLibraryManager server = new NetLibraryManager(globalConfig);
int host = server.AddHost(topology, port, ip);
byte[] buffer = new byte[1024];
NetworkEventType netEvent;
while (processActive) {
while ((netEvent = server.Receive(out int hostID, out int connectionID, out int channelID, buffer, buffer.Length, out int dataLength, out byte netError)) != NetworkEventType.Nothing) {
switch (netEvent) {
case NetworkEventType.DataEvent:
if (channelID == 0) {
Interlocked.Increment(ref serverReliableReceived);
Interlocked.Add(ref serverReliableBytesReceived, dataLength);
server.Send(hostID, connectionID, reliableChannel, messageData, messageData.Length, out byte sendError);
Interlocked.Increment(ref serverReliableSent);
Interlocked.Add(ref serverReliableBytesSent, messageData.Length);
} else if (channelID == 1) {
Interlocked.Increment(ref serverUnreliableReceived);
Interlocked.Add(ref serverUnreliableBytesReceived, dataLength);
server.Send(hostID, connectionID, unreliableChannel, reversedData, reversedData.Length, out byte sendError);
Interlocked.Increment(ref serverUnreliableSent);
Interlocked.Add(ref serverUnreliableBytesSent, reversedData.Length);
}
break;
}
}
Thread.Sleep(1000 / serverTickRate);
}
}
public static async Task Client() {
await Task.Factory.StartNew(() => {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.ThreadPoolSize = 1;
globalConfig.ThreadAwakeTimeout = (uint)clientTickRate;
globalConfig.MaxHosts = 1;
globalConfig.MaxPacketSize = (ushort)((messageData.Length * 2) + 32);
globalConfig.ReactorMaximumSentMessages = (ushort)(sendRate / 2);
globalConfig.ReactorMaximumReceivedMessages = (ushort)(sendRate / 2);
ConnectionConfig connectionConfig = new ConnectionConfig();
int reliableChannel = connectionConfig.AddChannel(QosType.ReliableSequenced);
int unreliableChannel = connectionConfig.AddChannel(QosType.UnreliableSequenced);
connectionConfig.SendDelay = 1;
connectionConfig.MinUpdateTimeout = 1;
connectionConfig.PingTimeout = 2000;
connectionConfig.DisconnectTimeout = 5000;
connectionConfig.PacketSize = (ushort)((messageData.Length * 2) + 32);
HostTopology topology = new HostTopology(connectionConfig, 1);
topology.SentMessagePoolSize = (ushort)(sendRate / 2);
topology.ReceivedMessagePoolSize = (ushort)(sendRate / 2);
NetLibraryManager client = new NetLibraryManager(globalConfig);
int host = client.AddHost(topology, 0, null);
int connection = client.Connect(host, ip, port, 0, out byte connectionError);
int reliableToSend = 0;
int unreliableToSend = 0;
Task.Factory.StartNew(async() => {
bool reliableIncremented = false;
bool unreliableIncremented = false;
while (processActive) {
if (reliableToSend > 0) {
client.Send(host, connection, reliableChannel, messageData, messageData.Length, out byte sendError);
Interlocked.Decrement(ref reliableToSend);
Interlocked.Increment(ref clientsReliableSent);
Interlocked.Add(ref clientsReliableBytesSent, messageData.Length);
}
if (unreliableToSend > 0) {
client.Send(host, connection, unreliableChannel, reversedData, reversedData.Length, out byte sendError);
Interlocked.Decrement(ref unreliableToSend);
Interlocked.Increment(ref clientsUnreliableSent);
Interlocked.Add(ref clientsUnreliableBytesSent, reversedData.Length);
}
if (reliableToSend > 0 && !reliableIncremented) {
reliableIncremented = true;
Interlocked.Increment(ref clientsStreamsCount);
} else if (reliableToSend == 0 && reliableIncremented) {
reliableIncremented = false;
Interlocked.Decrement(ref clientsStreamsCount);
}
if (unreliableToSend > 0 && !unreliableIncremented) {
unreliableIncremented = true;
Interlocked.Increment(ref clientsStreamsCount);
} else if (unreliableToSend == 0 && unreliableIncremented) {
unreliableIncremented = false;
Interlocked.Decrement(ref clientsStreamsCount);
}
await Task.Delay(1000 / sendRate);
}
}, TaskCreationOptions.AttachedToParent);
byte[] buffer = new byte[1024];
NetworkEventType netEvent;
while (processActive) {
while ((netEvent = client.Receive(out int hostID, out int connectionID, out int channelID, buffer, buffer.Length, out int dataLength, out byte netError)) != NetworkEventType.Nothing) {
switch (netEvent) {
case NetworkEventType.ConnectEvent:
Interlocked.Increment(ref clientsConnectedCount);
Interlocked.Exchange(ref reliableToSend, reliableMessages);
Interlocked.Exchange(ref unreliableToSend, unreliableMessages);
break;
case NetworkEventType.DisconnectEvent:
Interlocked.Increment(ref clientsDisconnectedCount);
Interlocked.Exchange(ref reliableToSend, 0);
Interlocked.Exchange(ref unreliableToSend, 0);
break;
case NetworkEventType.DataEvent: