-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNetworkService.cs
More file actions
1397 lines (1222 loc) · 57.9 KB
/
NetworkService.cs
File metadata and controls
1397 lines (1222 loc) · 57.9 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.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace LightNet
{
public enum ENetChannel
{
/// <summary>
/// Messages of this kind will always reach their destination
/// (given the connection is not lost) in the exact same order
/// they were send in.
/// </summary>
Reliable,
/// <summary>
/// Messages of this kind might or might not reach their destination,
/// but for the ones arriving their order is still assured.
/// </summary>
Unreliable
}
public enum ENetworkState
{
Closed,
Startup,
Running,
Shutdown
}
/// <summary>
/// Use these flags to determine what kind of events should be tracked
/// </summary>
[Flags]
public enum ENetworkEventReportFlags : byte
{
None = 0x00,
ConnectionStatus = 0x01,
ReceivedMessage = 0x02,
All = ConnectionStatus | ReceivedMessage
}
/// <summary>
/// Connection handles can be seen as a unique identifier of a single connection.<br/>
/// As a client, you will always only have one connection (the one to the server).<br/>
/// As a server, you're likely managing multiple connections at once, so if e.g. you got
/// four clients connected to you, there will be four distinct connection handles.
/// A handle:<br/>
/// - is always unique<br/>
/// - will never be re-assigned<br/>
/// - can become invalid over time (e.g. through connection loss)
/// </summary>
public struct ConnectionHandle
{
public ConnectionHandle(ulong internalHandle)
{
Handle = internalHandle;
}
public ulong GetInternalHandle()
{
return Handle;
}
/// <summary>
/// NOTE: This is only checking whether you've been handed a valid handle in the first place!<br/>
/// It does NOT check whether the connection behind this handle is still in existence or not!<br/>
/// To check the connection state, use <see cref="NetworkService.IsAlive"/>
/// </summary>
public bool IsValid()
{
return Handle != 0;
}
// Get's incremented for each new handle over time.
// Using uint64 should be enough to not overflow at any reasonable time.
ulong Handle;
}
public struct ConnectionEvent
{
public enum EType
{
Connected,
Disconnected,
ReceivedMessage
}
public EType EventType;
public ConnectionHandle Connection;
}
/// <summary>
/// A platform agnostic, multi threaded, multi channel, leightweight network library, using queued
/// events for multi threadable and platform independent event retrieval.<br/>
/// NOTE: In case of using this library on another platform than Unity, you NEED to re-route
/// <see cref="ASSERT"/> and <see cref="CLAMP"/> appropriately!
/// </summary>
public class NetworkService
{
// ASSERT and CLAMP are the only platform specific dependencies.
// Route them to somewhere else to make this library completely platform independent!
static void ASSERT(bool condition) { UnityEngine.Debug.Assert(condition); }
// This is stupid... the .NET runtime of Unity doesn't implement System.Math.Clamp, so we have
// to re-route to Unitys Math library instead. When using on a different platform, re-route appropriately
static int CLAMP(int value, int min, int max) { return UnityEngine.Mathf.Clamp(value, min, max); }
// This should be enough for most cases.
// Increase in case of 'Ran out of receive buffer memory!' error.
const int CHANNEL_BUFFER_SIZE = 2048;
// Milliseconds
const int SHUTDOWN_TIMEOUT = 2000;
// Milliseconds
const int PING_INTERVAL = 1000;
// Seconds. Timeout when to deem a connection as lost after not receiving any ping
const double PING_TIMEOUT = 5.0;
// If any internal queue (receive queues, event queue) exceeds this size,
// a warning will be issued. When this happens it probably is due to the
// application not polling any network data / events
const int QUEUE_WARN_THRESHOLD = 1000;
// Internal header for all reliable packages
enum EMessageType : byte
{
INVALID = 0,
Ping,
Disconnect,
ClientInfo,
Message
}
/// <summary>
/// Specify what kind of events should be pushed into the event queue by setting the appropriate flag(s)
/// </summary>
public volatile ENetworkEventReportFlags EventFlags = ENetworkEventReportFlags.ConnectionStatus;
volatile ENetworkState State = ENetworkState.Closed;
volatile bool bShutdown = true;
volatile int NetworkErrorEmulationLevel = 0; // 0 - 100
volatile int NetworkErrorEmulationDelay = 0; // milliseconds
volatile TcpListener Server;
volatile UdpClient UnreliableReceive;
Thread NetThread;
ulong NextConnectionHandle = 1;
int PortReliable;
int PortUnreliable;
IPAddress RemoteAddress;
ConcurrentQueue<int> FreeUnreliablePorts = new ConcurrentQueue<int>();
ConcurrentDictionary<ulong, Connection> Connections = new ConcurrentDictionary<ulong, Connection>();
ConcurrentQueue<ConnectionEvent> Events = new ConcurrentQueue<ConnectionEvent>();
static readonly System.Random Rand = new System.Random();
~NetworkService()
{
if (State == ENetworkState.Running || State == ENetworkState.Startup)
{
Close();
}
}
/// <summary>
/// Start a server, listening to incoming clients
/// </summary>
/// <param name="portReliable">Port to build up the reliable (TCP) connection on</param>
/// <param name="portUnreliable">
/// Port to build the unreliable (UDP) connection on.<br/>
/// Beware that, with the current implementation, each new client will listen on a subsequent
/// port after the given one! So for example, for portUnreliable=69, the first client will listen
/// on UDP port 70, the next on 71 and so on...
/// </param>
/// <param name="maxClients">Maximum of connections to accept</param>
/// <returns>False, if already running or starting the server failed (port already in use?)</returns>
public bool StartServer(int portReliable, int portUnreliable, int maxClients)
{
if (State != ENetworkState.Closed)
{
LogQueue.LogWarning("Cannot start Server, we're already a {}!", new object[] { State });
return false;
}
ASSERT(Server == null);
ASSERT(UnreliableReceive == null);
ASSERT(Connections.Count == 0);
PortReliable = portReliable;
PortUnreliable = portUnreliable;
while (FreeUnreliablePorts.TryDequeue(out int _)) { }
for (int i = 1; i <= maxClients; ++i)
{
FreeUnreliablePorts.Enqueue(PortUnreliable + i);
}
while (Events.TryDequeue(out ConnectionEvent _)) { }
Server = new TcpListener(new IPEndPoint(IPAddress.Any, portReliable));
try
{
// will fail if the port is already occupied
Server.Start(maxClients);
}
catch (Exception e)
{
LogQueue.LogWarning(e.Message);
Server.Stop();
Server = null;
State = ENetworkState.Closed;
return false;
}
UnreliableReceive = new UdpClient(portUnreliable);
bShutdown = false;
NetThread = new Thread(ServerThreadFunc);
NetThread.Name = "Lightnet_ServerThread";
NetThread.Start();
State = ENetworkState.Running;
return true;
}
/// <summary>
/// Connect as a client to a already listening server
/// </summary>
/// <param name="address">The address to connect to</param>
/// <param name="portReliable">Port of the reliable (TCP) connection the server listens on</param>
/// <param name="portUnreliable">Port of the unreliable (UDP) connection the server listens on</param>
/// <returns>False, if already running</returns>
public bool StartClient(IPAddress address, int portReliable, int portUnreliable)
{
if (State != ENetworkState.Closed)
{
LogQueue.LogWarning("Cannot start Client, we're already a {}!", new object[] { State });
return false;
}
ASSERT(Server == null);
ASSERT(UnreliableReceive == null);
ASSERT(Connections.Count == 0);
State = ENetworkState.Startup;
RemoteAddress = address;
PortReliable = portReliable;
PortUnreliable = portUnreliable;
while (Events.TryDequeue(out ConnectionEvent e)) { }
bShutdown = false;
NetThread = new Thread(ClientThreadFunc);
NetThread.Name = "Lightnet_ClientThread";
NetThread.Start();
return true;
}
public ENetworkState GetState()
{
return State;
}
/// <summary>
/// Note that this method will return false as default, meaning it also does when the networking is not running at all.<br/>
/// </summary>
/// <returns>TRUE if and only if we are running networking as Server!</returns>
public bool IsServer()
{
return Server != null;
}
/// <summary>
/// Close all open connections and shut down all sockets.<br/>
/// This is for both roles, server and client.
/// </summary>
/// <returns>False, if we're already in the process of shutting down or already closed altogether.</returns>
public bool Close()
{
if (State == ENetworkState.Closed)
{
LogQueue.LogWarning("Cannot close networking, already closed!");
return false;
}
if (State == ENetworkState.Shutdown)
{
LogQueue.LogWarning("Cannot close networking, already shutting down...");
return false;
}
ASSERT(!bShutdown);
ASSERT(NetThread != null);
ASSERT(NetThread.IsAlive);
State = ENetworkState.Shutdown;
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
conn.Value.SendDisconnect();
}
bShutdown = true;
void AbortThreads()
{
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
conn.Value.Shutdown();
}
Connections.Clear();
// Do not join NetThread if we ARE the NetThread
if (Thread.CurrentThread != NetThread)
{
if (!NetThread.Join(SHUTDOWN_TIMEOUT))
{
NetThread.Abort();
}
NetThread = null;
}
State = ENetworkState.Closed;
}
Thread abortThread = new Thread(AbortThreads);
abortThread.Start();
Server?.Stop();
Server = null;
UnreliableReceive?.Close();
UnreliableReceive = null;
return true;
}
/// <summary>
/// Intentionally disconnect from one specific peer.<br/>
/// If we're a running client, this call is synonymous with calling <see cref="Close"/>.
/// </summary>
/// <param name="connection">The connection you want to close.</param>
/// <returns>False, if the given connection is unknown, e.g. due to not longer being alive (already closed).</returns>
public bool Disconnect(ConnectionHandle connection)
{
if ((State == ENetworkState.Startup || State == ENetworkState.Running) && !IsServer())
{
return Close();
}
if (!Connections.TryRemove(connection.GetInternalHandle(), out Connection conn))
{
LogQueue.LogWarning($"Cannot close an unknown connection. Already disconnected?");
return false;
}
conn.SendDisconnect();
conn.Shutdown();
FreeUnreliablePorts.Enqueue(conn.RemoteUnreliable.Port);
return true;
}
/// <summary>
/// Emulate bad network via loosing some packages intentionally and delaying their delivery
/// </summary>
/// <param name="looseLevel">0 = no packages get lost, 100 = all packages get lost</param>
/// <param name="maxSendDelay">
/// maximum delay to wait before sending/receiving a package in milliseconds
/// (will be chosen randomly for each package between 0 and maxSendDelay)
/// </param>
public void SetNetworkErrorEmulation(int looseLevel, int maxSendDelay)
{
NetworkErrorEmulationLevel = CLAMP(looseLevel, 0, 100);
NetworkErrorEmulationDelay = Math.Min(maxSendDelay, 0);
}
/// <summary>
/// Get handles for all the currently established connections at this exact point in time.<br/>
/// For clients, there should always be 0 (disconnected) or 1 (connected) connections.<br/>
/// For servers, this can vary from 0 to maxClients.
/// </summary>
/// <returns>
/// A list of connection handles. A connection handle can be seen as a unique identifier of
/// a single connection.<br/>
/// A handle:<br/>
/// - is always unique<br/>
/// - will never be re-assigned<br/>
/// - can become invalid over time
/// </returns>
public ConnectionHandle[] GetConnections()
{
ConnectionHandle[] conns = new ConnectionHandle[Connections.Count];
int i = 0;
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
conns[i++] = new ConnectionHandle(conn.Key);
}
return conns;
}
/// <summary>
/// Returns the 'name' of a given connection. This usually contains the remote address,
/// the connected ports, and whether that connection is still alive or not.
/// </summary>
/// <param name="handle">Connection you want to retrieve the name / information from</param>
/// <returns>"INVALID HANDLE" if the given connection handle is invalid</returns>
public string GetConnectionName(ConnectionHandle handle)
{
if (!handle.IsValid() || !Connections.ContainsKey(handle.GetInternalHandle()))
{
LogQueue.LogWarning("Given connection handle was invalid!");
return "INVALID HANDLE";
}
return Connections[handle.GetInternalHandle()].ToString();
}
/// <summary>
/// Here you can check whether a connection, you polled at some point in the past using <see cref="GetConnections"/>,
/// is still alive (connected).
/// </summary>
public bool IsAlive(ConnectionHandle handle)
{
return handle.IsValid() && Connections.ContainsKey(handle.GetInternalHandle()) && Connections[handle.GetInternalHandle()].IsAlive();
}
/// <summary>
/// There will be "connected", "disconnected" and "package received" events which you can poll here.
/// You can determine what kind of events should be tracked by setting the <see cref="EventFlags"/> appropriately.
/// </summary>
/// <param name="outEvent"></param>
/// <returns></returns>
public bool GetNextEvent(out ConnectionEvent outEvent)
{
return Events.TryDequeue(out outEvent);
}
/// <summary>
/// Send a message through a specific connection / to a specific destination.
/// </summary>
/// <param name="connection">Destination of this message</param>
/// <param name="channel">Choose whether you want this message to be transmitted reliable or not</param>
/// <param name="message">The actual message</param>
/// <returns>False, if the given connection handle is (no longer) valid.</returns>
public bool SendMessage(ConnectionHandle connection, ENetChannel channel, byte[] message)
{
if (!Connections.TryGetValue(connection.GetInternalHandle(), out Connection conn))
{
LogQueue.LogWarning("Given connection handle is invalid!");
return false;
}
conn.SendMessage(channel, message);
return true;
}
/// <summary>
/// Send a message to everyone listening.
/// </summary>
/// <param name="channel">Choose whether you want this message to be transmitted reliable or not</param>
/// <param name="message">The actual message you want to spread</param>
public void BroadcastMessage(ENetChannel channel, byte[] message)
{
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
if (conn.Value.IsAlive())
{
conn.Value.SendMessage(channel, message);
}
}
}
/// <summary>
/// Try to get the next message received by the given connection, on a specific channel.
/// </summary>
/// <param name="connection">The connection to try get a message from</param>
/// <param name="channel">The channel to try get a message from</param>
/// <param name="message">The received message data</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(ConnectionHandle connection, ENetChannel channel, out byte[] message)
{
if (!Connections.TryGetValue(connection.GetInternalHandle(), out Connection conn))
{
message = null;
LogQueue.LogWarning("Given connection handle is invalid!");
return false;
}
return conn.GetNextMessage(channel, out message);
}
/// <summary>
/// Try to get the next message received by the given connection, on any channel.
/// </summary>
/// <param name="connection">The connection to try get a message from</param>
/// <param name="message">The received message data</param>
/// <param name="channel">The channel on which we received the message</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(ConnectionHandle connection, out byte[] message, out ENetChannel channel)
{
if (!Connections.TryGetValue(connection.GetInternalHandle(), out Connection conn))
{
channel = ENetChannel.Unreliable;
message = null;
LogQueue.LogWarning("Given connection handle is invalid!");
return false;
}
return conn.GetNextMessage(out message, out channel);
}
/// <summary>
/// Try to get the next message received by the given connection, on any channel.
/// </summary>
/// <param name="connection">The connection to try get a message from</param>
/// <param name="message">The received message data</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(ConnectionHandle connection, out byte[] message)
{
if (!Connections.TryGetValue(connection.GetInternalHandle(), out Connection conn))
{
message = null;
LogQueue.LogWarning("Given connection handle is invalid!");
return false;
}
return conn.GetNextMessage(out message);
}
/// <summary>
/// Try to get the next message received by any connection, on any channel.
/// </summary>
/// <param name="message">The received message data</param>
/// <param name="connection">The connection we received the message from</param>
/// <param name="channel">The channel on which we received the message</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(out byte[] message, out ConnectionHandle connection, out ENetChannel channel)
{
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
connection = new ConnectionHandle(conn.Key);
if (conn.Value.GetNextMessage(out message, out channel))
{
return true;
}
}
message = null;
connection = new ConnectionHandle(0);
channel = ENetChannel.Unreliable;
return false;
}
/// <summary>
/// Try to get the next message received by any connection, on any channel.
/// </summary>
/// <param name="message">The received message data</param>
/// <param name="connection">The connection we received the message from</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(out byte[] message, out ConnectionHandle connection)
{
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
connection = new ConnectionHandle(conn.Key);
if (conn.Value.GetNextMessage(out message))
{
return true;
}
}
message = null;
connection = new ConnectionHandle(0);
return false;
}
/// <summary>
/// Try to get the next message received by any connection, on any channel.
/// </summary>
/// <param name="message">The received message data</param>
/// <returns>False, if there're no messages left</returns>
public bool GetNextMessage(out byte[] message)
{
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
if (conn.Value.GetNextMessage(out message))
{
return true;
}
}
message = null;
return false;
}
void AddEvent(ConnectionEvent ev, ENetworkEventReportFlags flag)
{
if ((EventFlags & flag) != 0)
{
Events.Enqueue(ev);
if (Events.Count > QUEUE_WARN_THRESHOLD)
{
LogQueue.LogWarning("NetworkService event queue has over {0} events queued! Do you poll them somewhere?");
}
}
}
void ServerThreadFunc()
{
ASSERT(Server != null);
ASSERT(State == ENetworkState.Running);
ASSERT(Connections.Count == 0);
while (!bShutdown)
{
// check for incoming connections
if (Server.Pending())
{
TcpClient client = null;
try
{
// this will block the thread until someone connects
// gladfully, we checked with Pending() beforehand if
// there's someone knocking on the door
client = Server.AcceptTcpClient();
}
catch (Exception e)
{
LogQueue.LogWarning(e.Message);
continue;
}
ASSERT(client != null);
IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
ASSERT(FreeUnreliablePorts.Count > 0);
ASSERT(FreeUnreliablePorts.TryDequeue(out int clientListenPort));
ulong handle = NextConnectionHandle++;
Connection conn = new Connection(this, handle, address, PortReliable, clientListenPort, client);
if (!Connections.TryAdd(handle, conn))
{
LogQueue.LogError("Connection handles are inconsistent! This should never happen!");
Close();
return;
}
LogQueue.LogInfo("New client '{0}' joined (handle: {1})", new object[] { address.ToString(), handle });
AddEvent(new ConnectionEvent
{
Connection = new ConnectionHandle(handle),
EventType = ConnectionEvent.EType.Connected
}, ENetworkEventReportFlags.ConnectionStatus);
}
foreach (KeyValuePair<ulong, Connection> conn in Connections)
{
if (!conn.Value.IsAlive())
{
if (!conn.Value.IsIntentionalDisconnect())
{
LogQueue.LogInfo("Connection to '{0}' lost!", new object[] { conn.Value.GetRemoteAddress().ToString() });
}
conn.Value.Shutdown();
if (!Connections.TryRemove(conn.Key, out Connection c))
{
LogQueue.LogError("Inconsitent connection dictionary! This should never happen!");
}
AddEvent(new ConnectionEvent
{
Connection = new ConnectionHandle(conn.Key),
EventType = ConnectionEvent.EType.Disconnected
}, ENetworkEventReportFlags.ConnectionStatus);
}
}
ReceiveUnreliable();
}
}
void ClientThreadFunc()
{
const ulong handle = 1;
ASSERT(Server == null);
ASSERT(UnreliableReceive == null);
ASSERT(State == ENetworkState.Startup);
ASSERT(Connections.Count == 0);
TcpClient client = null;
try
{
// try connect to specified remote
client = new TcpClient();
client.Connect(new IPEndPoint(RemoteAddress, PortReliable));
if (!client.Connected)
{
Connections.Clear();
LogQueue.LogWarning("Couldn't connect to Server '{0}'!", new object[] { RemoteAddress.ToString() });
Close();
return;
}
}
catch (Exception e)
{
LogQueue.LogWarning(e.Message);
Close();
return;
}
Connections.TryAdd(handle, new Connection(this, handle, RemoteAddress, PortReliable, PortUnreliable, client));
ASSERT(Connections.Count == 1);
State = ENetworkState.Running;
AddEvent(new ConnectionEvent
{
Connection = new ConnectionHandle(handle),
EventType = ConnectionEvent.EType.Connected
}, ENetworkEventReportFlags.ConnectionStatus);
while (!bShutdown)
{
if (!Connections[handle].IsAlive())
{
if (!Connections[handle].IsIntentionalDisconnect())
{
LogQueue.LogWarning("Connection to Server '{0}' lost!", new object[] { Connections[handle].GetRemoteAddress().ToString() });
}
Connections[handle].Shutdown();
Connections.Clear();
AddEvent(new ConnectionEvent
{
Connection = new ConnectionHandle(handle),
EventType = ConnectionEvent.EType.Disconnected
}, ENetworkEventReportFlags.ConnectionStatus);
Close();
return;
}
ReceiveUnreliable();
}
}
void ReceiveUnreliable()
{
if (UnreliableReceive == null)
{
return;
}
// RECEIVING - UDP
while (UnreliableReceive.Available > 0)
{
IPEndPoint sender = null;
byte[] data = null;
try
{
// using the sender as identification is unreliable,
// especially when dealing with local connections
data = UnreliableReceive.Receive(ref sender);
}
catch (Exception e)
{
LogQueue.LogWarning("UDP Receiving failed: " + e.Message);
return;
}
Connection connection = null;
ASSERT(data != null);
ASSERT(sender != null);
//LogQueue.LogInfo("Received UDP package: {0}", new object[] { data.Length });
int offset = 0;
if (Server != null)
{
// for servers, we expect the clients to always send a ulong
// beforehand, specifying the connection handle we assigned to them
ulong handle = BitConverter.ToUInt64(data, 0); offset += sizeof(ulong);
connection = Connections[handle];
}
else
{
// for clients, there's always just one connection
// and it's handle is always 1
connection = Connections[1];
}
ASSERT(connection != null);
lock (connection.GetUnreliableReceiveLock())
{
Connection.ReceiveBuffer buffer = connection.GetUnreliableReceiveBuffer();
int maxReadSize = CHANNEL_BUFFER_SIZE - buffer.Head;
if (data.Length > maxReadSize)
{
LogQueue.LogError("Ran out of unreliable receive buffer memory! Message too large?");
return;
}
Array.Copy(data, offset, buffer.Buffer, buffer.Head, data.Length - offset);
buffer.Head += data.Length;
}
}
}
class Connection
{
public class ReceiveBuffer
{
public byte[] Buffer = new byte[CHANNEL_BUFFER_SIZE];
public int Head;
}
public IPEndPoint RemoteUnreliable { get; private set; }
IPEndPoint RemoteReliable;
NetworkService Owner = null;
ulong Handle = 0;
ulong RemoteHandle = 0;
volatile bool bIntentionalDisconnect;
volatile bool bShutdown = false;
volatile Thread ConnectionThread;
volatile TcpClient Reliable;
Thread PingThread;
UdpClient UnrealiableSend;
ulong UnreliableTime = 0;
DateTime LastPing;
object AliveLock = new object();
object UnreliableReceiveLock = new object();
// Tcp packets will already arrive sorted (order is guaranteed), no additional sorting needed.
// For udp packets, we're using timestamps to determine the order of the packet.
ConcurrentQueue<byte[]> ReceivedReliableMessages = new ConcurrentQueue<byte[]>();
ConcurrentSortedQueue<ulong, byte[]> ReceivedUnreliableMessages = new ConcurrentSortedQueue<ulong, byte[]>();
// Message layout:
// 2 bytes (ushort) - message length (number of bytes)
// rest of data - actual message
ReceiveBuffer ReliableReceiveBuffer = new ReceiveBuffer();
// Message layout:
// 8 bytes (ulong) - timestamp
// 2 bytes (ushort) - message length (number of bytes)
// rest of data - actual message
ReceiveBuffer UnreliableReceiveBuffer = new ReceiveBuffer();
// these contain just message data, without header (a.k.a. timestamp and message length)
ConcurrentQueue<byte[]> ReliableSendBuffer = new ConcurrentQueue<byte[]>();
ConcurrentQueue<byte[]> UnreliableSendBuffer = new ConcurrentQueue<byte[]>();
public Connection(NetworkService owner, ulong handle, IPAddress address, int portReliable, int portUnreliable, TcpClient client)
{
ASSERT(owner != null);
ASSERT(handle != 0);
ASSERT(client != null);
Owner = owner;
Handle = handle;
RemoteReliable = new IPEndPoint(address, portReliable);
RemoteUnreliable = new IPEndPoint(address, portUnreliable);
Reliable = client;
LastPing = DateTime.Now;
ConnectionThread = new Thread(ConnectionThreadFunc);
ConnectionThread.Name = "Lightnet_" + ToString();
ConnectionThread.Start();
if (Owner.Server != null)
{
// Server only:
// FIRST thing to send to our new client is the handle we are giving them.
// This is necessary to later resolve an incoming UDP package to a specific connection
SendClientInfo();
}
PingThread = new Thread(Ping);
PingThread.Name = "Lightnet_Ping_" + ToString();
PingThread.Start();
}
~Connection()
{
if (!bShutdown)
{
Shutdown();
}
}
public IPAddress GetRemoteAddress()
{
return RemoteReliable.Address;
}
public bool IsAlive()
{
bool bAlive = false;
lock (AliveLock)
{
bAlive = !bIntentionalDisconnect && Reliable.Connected && ConnectionThread.IsAlive;
}
return bAlive;
}
public bool IsIntentionalDisconnect()
{
return bIntentionalDisconnect;
}
public ReceiveBuffer GetUnreliableReceiveBuffer()
{
return UnreliableReceiveBuffer;
}
public object GetUnreliableReceiveLock()
{
return UnreliableReceiveLock;
}
public void Shutdown()
{
if (bShutdown)
{
LogQueue.LogWarning("Connection is already shut down!");
return;
}
bShutdown = true;
if (!ConnectionThread.Join(SHUTDOWN_TIMEOUT))
{
LogQueue.LogWarning("Shutdown timeout, aborting connection thread...");
ConnectionThread.Abort();
}
if (!PingThread.Join(SHUTDOWN_TIMEOUT))
{
LogQueue.LogWarning("Shutdown timeout, aborting ping thread...");
PingThread.Abort();
}
PingThread = null;
Reliable.Close();
UnrealiableSend.Close();
}
public bool GetNextMessage(ENetChannel channel, out byte[] data)
{
if (channel == ENetChannel.Reliable)
{
return ReceivedReliableMessages.TryDequeue(out data);
}
else if (channel == ENetChannel.Unreliable)
{
return ReceivedUnreliableMessages.TryDequeue(out data);
}
LogQueue.LogError("Unknown ENetChannel '{0}'!", new object[] { (int)channel });
data = null;
return false;
}
public bool GetNextMessage(out byte[] data, out ENetChannel channel)
{
if (ReceivedReliableMessages.TryDequeue(out data))
{
channel = ENetChannel.Reliable;
return true;
}
else if (ReceivedUnreliableMessages.TryDequeue(out data))
{
channel = ENetChannel.Unreliable;
return true;
}
channel = ENetChannel.Unreliable;
return false;
}
public bool GetNextMessage(out byte[] data)
{
return ReceivedReliableMessages.TryDequeue(out data) || ReceivedUnreliableMessages.TryDequeue(out data);
}
public void SendMessage(ENetChannel channel, byte[] data)
{
if (!IsAlive())
{
LogQueue.LogWarning("Cannot send message on a dead connection!");
return;
}
if (data.Length == 0)
{