forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetBase.cs
More file actions
563 lines (500 loc) · 18.7 KB
/
NetBase.cs
File metadata and controls
563 lines (500 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#if DEBUG
#define STATS_ENABLED
#endif
using System;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLib
{
public abstract class NetBase
{
internal delegate void OnMessageReceived(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint);
private struct FlowMode
{
public int PacketsPerSecond;
public int StartRtt;
}
protected enum NetEventType
{
Connect,
Disconnect,
Receive,
ReceiveUnconnected,
Error,
ConnectionLatencyUpdated,
DiscoveryRequest,
DiscoveryResponse
}
protected sealed class NetEvent
{
public NetPeer Peer;
public NetDataReader DataReader;
public NetEventType Type;
public NetEndPoint RemoteEndPoint;
public int AdditionalData;
public DisconnectReason DisconnectReason;
}
#if DEBUG
private struct IncomingData
{
public byte[] Data;
public NetEndPoint EndPoint;
public DateTime TimeWhenGet;
}
private readonly LinkedList<IncomingData> _pingSimulationList = new LinkedList<IncomingData>();
private readonly Random _randomGenerator = new Random();
#endif
private readonly NetSocket _socket;
private readonly List<FlowMode> _flowModes;
private NetThread _netThread;
private bool _running;
private readonly Queue<NetEvent> _netEventsQueue;
private readonly Stack<NetEvent> _netEventsPool;
private readonly INetEventListener _netEventListener;
//config section
public bool UnconnectedMessagesEnabled = false;
public bool NatPunchEnabled = false;
public int UpdateTime = 100;
public int ReliableResendTime = 500;
public int PingInterval = NetConstants.DefaultPingInterval;
public long DisconnectTimeout = 5000;
public bool SimulatePacketLoss = false;
public bool SimulateLatency = false;
public int SimulationPacketLossChance = 10;
public int SimulationMinLatency = 30;
public int SimulationMaxLatency = 100;
public bool UnsyncedEvents = false;
public bool DiscoveryEnabled = false;
//stats
public ulong PacketsSent { get; private set; }
public ulong PacketsReceived { get; private set; }
public ulong BytesSent { get; private set; }
public ulong BytesReceived { get; private set; }
//modules
public readonly NatPunchModule NatPunchModule;
public void AddFlowMode(int startRtt, int packetsPerSecond)
{
var fm = new FlowMode {PacketsPerSecond = packetsPerSecond, StartRtt = startRtt};
if (_flowModes.Count > 0 && startRtt < _flowModes[0].StartRtt)
{
_flowModes.Insert(0, fm);
}
else
{
_flowModes.Add(fm);
}
}
internal int GetPacketsPerSecond(int flowMode)
{
if (flowMode < 0 || _flowModes.Count == 0)
return NetConstants.PacketsPerSecondMax;
return _flowModes[flowMode].PacketsPerSecond;
}
internal int GetMaxFlowMode()
{
return _flowModes.Count - 1;
}
internal int GetStartRtt(int flowMode)
{
if (flowMode < 0 || _flowModes.Count == 0)
return 0;
return _flowModes[flowMode].StartRtt;
}
protected NetBase(INetEventListener listener)
{
_socket = new NetSocket(ReceiveLogic);
_netEventListener = listener;
_flowModes = new List<FlowMode>();
_netEventsQueue = new Queue<NetEvent>();
_netEventsPool = new Stack<NetEvent>();
NatPunchModule = new NatPunchModule(this, _socket);
}
protected void SocketClearPeers()
{
#if WINRT && !UNITY_EDITOR
_socket.ClearPeers();
#endif
}
protected void SocketRemovePeer(NetEndPoint ep)
{
#if WINRT && !UNITY_EDITOR
_socket.RemovePeer(ep);
#endif
}
protected NetPeer CreatePeer(NetEndPoint remoteEndPoint)
{
var peer = new NetPeer(this, remoteEndPoint);
peer.PingInterval = PingInterval;
return peer;
}
internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency)
{
var evt = CreateEvent(NetEventType.ConnectionLatencyUpdated);
evt.Peer = fromPeer;
evt.AdditionalData = latency;
EnqueueEvent(evt);
}
/// <summary>
/// Start logic thread and listening on available port
/// </summary>
public bool Start()
{
return Start(0);
}
/// <summary>
/// Start logic thread and listening on selected port
/// </summary>
/// <param name="port">port to listen</param>
public virtual bool Start(int port)
{
if (_running)
{
return false;
}
_netEventsQueue.Clear();
if (!_socket.Bind(port))
return false;
_socket.JoinMulticastGroup(NetConstants.MulticastGroupIPv4);
_socket.JoinMulticastGroup(NetConstants.MulticastGroupIPv6);
_running = true;
_netThread = new NetThread("LogicThread(" + port + ")", UpdateTime, UpdateLogic);
return true;
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, NetEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="writer">Data serializer</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(NetDataWriter writer, NetEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="start">data start</param>
/// <param name="length">data length</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, int start, int length, NetEndPoint remoteEndPoint)
{
if (!_running)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.UnconnectedMessage, message, start, length);
return SendRaw(packet, remoteEndPoint);
}
public bool SendDiscoveryRequest(NetDataWriter writer, int port)
{
return SendDiscoveryRequest(writer.Data, 0, writer.Length, port);
}
public bool SendDiscoveryRequest(byte[] data, int port)
{
return SendDiscoveryRequest(data, 0, data.Length, port);
}
public bool SendDiscoveryRequest(byte[] data, int start, int length, int port)
{
if (!_running)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.DiscoveryRequest, data, start, length);
return _socket.SendMulticast(packet, 0, packet.Length, port);
}
public bool SendDiscoveryResponse(NetDataWriter writer, NetEndPoint remoteEndPoint)
{
return SendDiscoveryResponse(writer.Data, 0, writer.Length, remoteEndPoint);
}
public bool SendDiscoveryResponse(byte[] data, NetEndPoint remoteEndPoint)
{
return SendDiscoveryResponse(data, 0, data.Length, remoteEndPoint);
}
public bool SendDiscoveryResponse(byte[] data, int start, int length, NetEndPoint remoteEndPoint)
{
if (!_running)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.DiscoveryResponse, data, start, length);
return SendRaw(packet, remoteEndPoint);
}
internal bool SendRaw(byte[] message, NetEndPoint remoteEndPoint)
{
return SendRaw(message, 0, message.Length, remoteEndPoint);
}
internal bool SendRaw(byte[] message, int start, int length, NetEndPoint remoteEndPoint)
{
if (!_running)
return false;
int errorCode = 0;
bool result = _socket.SendTo(message, start, length, remoteEndPoint, ref errorCode) > 0;
//10040 message to long... need to check
//10065 no route to host
if (errorCode != 0 && errorCode != 10040 && errorCode != 10065)
{
ProcessSendError(remoteEndPoint, errorCode);
return false;
}
if (errorCode == 10040)
{
NetUtils.DebugWrite(ConsoleColor.Red, "[SRD] 10040, datalen: {0}", length);
return false;
}
#if STATS_ENABLED
PacketsSent++;
BytesSent += (uint)length;
#endif
return result;
}
/// <summary>
/// Stop updating thread and listening
/// </summary>
public virtual void Stop()
{
if (_running)
{
_running = false;
_netThread.Stop();
_socket.Close();
}
}
/// <summary>
/// Returns true if socket listening and update thread is running
/// </summary>
public bool IsRunning
{
get { return _running; }
}
/// <summary>
/// Returns local EndPoint (host and port)
/// </summary>
public NetEndPoint LocalEndPoint
{
get { return _socket.LocalEndPoint; }
}
protected NetEvent CreateEvent(NetEventType type)
{
NetEvent evt = null;
lock (_netEventsPool)
{
if (_netEventsPool.Count > 0)
{
evt = _netEventsPool.Pop();
}
}
if(evt == null)
{
evt = new NetEvent {DataReader = new NetDataReader()};
}
evt.Type = type;
return evt;
}
protected void EnqueueEvent(NetEvent evt)
{
if (UnsyncedEvents)
{
ProcessEvent(evt);
}
else
{
lock (_netEventsQueue)
{
_netEventsQueue.Enqueue(evt);
}
}
}
private void ProcessEvent(NetEvent evt)
{
switch (evt.Type)
{
case NetEventType.Connect:
_netEventListener.OnPeerConnected(evt.Peer);
break;
case NetEventType.Disconnect:
_netEventListener.OnPeerDisconnected(evt.Peer, evt.DisconnectReason, evt.AdditionalData);
break;
case NetEventType.Receive:
_netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader);
break;
case NetEventType.ReceiveUnconnected:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Default);
break;
case NetEventType.DiscoveryRequest:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryRequest);
break;
case NetEventType.DiscoveryResponse:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryResponse);
break;
case NetEventType.Error:
_netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.AdditionalData);
break;
case NetEventType.ConnectionLatencyUpdated:
_netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.AdditionalData);
break;
}
//Recycle
evt.DataReader.Clear();
evt.Peer = null;
evt.AdditionalData = 0;
evt.RemoteEndPoint = null;
lock (_netEventsPool)
{
_netEventsPool.Push(evt);
}
}
public void PollEvents()
{
if (UnsyncedEvents)
return;
while (_netEventsQueue.Count > 0)
{
NetEvent evt;
lock (_netEventsQueue)
{
evt = _netEventsQueue.Dequeue();
}
ProcessEvent(evt);
}
}
//Update function
private void UpdateLogic()
{
_netThread.SleepTime = UpdateTime;
#if DEBUG
if (SimulateLatency)
{
var node = _pingSimulationList.First;
var time = DateTime.UtcNow;
while (node != null)
{
var incomingData = node.Value;
if (incomingData.TimeWhenGet <= time)
{
DataReceived(incomingData.Data, incomingData.Data.Length, incomingData.EndPoint);
var nodeToRemove = node;
node = node.Next;
lock (_pingSimulationList)
_pingSimulationList.Remove(nodeToRemove);
}
else
{
node = node.Next;
}
}
}
#endif
PostProcessEvent(UpdateTime);
}
private void ReceiveLogic(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint)
{
//Receive some info
if (errorCode == 0)
{
#if DEBUG
bool receivePacket = true;
if (SimulatePacketLoss && _randomGenerator.Next(100/SimulationPacketLossChance) == 0)
{
receivePacket = false;
}
else if (SimulateLatency)
{
int latency = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency);
if (latency > 5)
{
byte[] holdedData = new byte[length];
Buffer.BlockCopy(data, 0, holdedData, 0, length);
lock(_pingSimulationList)
_pingSimulationList.AddFirst(new IncomingData
{
Data = holdedData, EndPoint = remoteEndPoint, TimeWhenGet = DateTime.UtcNow.AddMilliseconds(latency)
});
receivePacket = false;
}
}
if (receivePacket) //DataReceived
#endif
//ProcessEvents
DataReceived(data, length, remoteEndPoint);
}
else
{
ProcessReceiveError(errorCode);
Stop();
}
}
private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
{
#if STATS_ENABLED
PacketsReceived++;
BytesReceived += (uint) count;
#endif
//Try get packet property
PacketProperty property;
if (!NetPacket.GetPacketProperty(reusableBuffer, out property))
return;
//Check unconnected
switch (property)
{
case PacketProperty.DiscoveryRequest:
if(DiscoveryEnabled)
{
var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.DiscoveryResponse:
{
var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.UnconnectedMessage:
if (UnconnectedMessagesEnabled)
{
var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.NatIntroduction:
case PacketProperty.NatIntroductionRequest:
case PacketProperty.NatPunchMessage:
{
if (NatPunchEnabled)
NatPunchModule.ProcessMessage(remoteEndPoint, property, NetPacket.GetUnconnectedData(reusableBuffer, count));
return;
}
}
//other
ReceiveFromSocket(reusableBuffer, count, remoteEndPoint);
}
protected virtual void ProcessReceiveError(int socketErrorCode)
{
var netEvent = CreateEvent(NetEventType.Error);
netEvent.AdditionalData = socketErrorCode;
EnqueueEvent(netEvent);
}
internal virtual void ProcessSendError(NetEndPoint endPoint, int socketErrorCode)
{
var netEvent = CreateEvent(NetEventType.Error);
netEvent.RemoteEndPoint = endPoint;
netEvent.AdditionalData = socketErrorCode;
EnqueueEvent(netEvent);
}
protected abstract void ReceiveFromSocket(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint);
protected abstract void PostProcessEvent(int deltaTime);
internal abstract void ReceiveFromPeer(NetPacket packet, NetEndPoint endPoint);
}
}