-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathConnection.cs
840 lines (806 loc) · 23 KB
/
Connection.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
// 2014.04
// Tracy Ma
// Original c++ version author: Glenn Fiedler <[email protected]>
using UnityEngine;
using System.Collections.Generic;
public class Address
{
// public bool Equals(Address other)
// {
// if()
// }
public Address()
{
_address = 0;
_port = 0;
}
public Address(char a, char b, char c, char d, ushort port)
{
_address = (uint)(a << 24);
_address |= (uint)(b << 16);
_address |= (uint)(c << 8);
_address |= (uint)(d);
_port = port;
}
public Address(uint address, ushort port)
{
_address = address;
_port = port;
}
public uint GetAddress()
{
return _address;
}
public ushort GetPort()
{
return _port;
}
public override bool Equals(System.Object obj)
{
if (obj == null)
{
return false;
}
Address a = obj as Address;
if ((System.Object)a == null)
{
return false;
}
return (_address == a._address) && (_port == a._port);
}
public override int GetHashCode()
{
return (int)(_address ^ _port);
}
public static bool operator ==(Address one, Address other)
{
return one._address == other._address && one._port == other._port;
}
public static bool operator !=(Address one, Address other)
{
return !(one == other);
}
public static bool operator <(Address one, Address other)
{
if (one._address < other._address)
return true;
if (one._address > other._address)
return false;
else
return one._port < other._port;
}
public static bool operator >(Address one, Address other)
{
if (one._address > other._address)
return true;
if (one._address < other._address)
return false;
else
return one._port > other._port;
}
public void Reset()
{
_address = 0;
_port = 0;
}
uint _address;
ushort _port;
}
public class Socket
{
public Socket()
{
socket = null;
}
~Socket()
{
Close();
}
/// <summary>
/// 初始化套接字和sendorRemote
/// </summary>
/// <param name="port">端口</param>
/// <returns></returns>
public bool Open(ushort port)
{
socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
socket.Blocking = false;
return true;
}
public void Close()
{
socket.Close();
}
//public bool IsOpen()
//{
// return socket.Available();
//}
public bool Send(ref System.Net.IPEndPoint ipep, byte[] data, int size)
{
if (socket == null)
{
return false;
}
int count = socket.SendTo(data, size, System.Net.Sockets.SocketFlags.None, ipep);
if (count > 0)
return true;
else
return false;
}
public int Receive(ref System.Net.EndPoint sendor, byte[] data, int size)
{
int count = socket.ReceiveFrom(data, ref sendor);
return count;
}
System.Net.Sockets.Socket socket = null;
}
public class Connection
{
public enum Mode
{
None,
Server,
Client
};
Mode mode;
uint protocolID;
float timeout;
bool running;
enum State
{
Disconnected,
Listening,
Connecting,
ConnectFail,
Connected
};
State state;
float timeoutAccumulator;
Socket socket = new Socket();
System.Net.IPEndPoint address = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 1912);
void ClearData()
{
state = State.Disconnected;
timeoutAccumulator = 0.0f;
//address.Reset();
}
protected virtual void OnStart() { }
protected virtual void OnStop() { }
protected virtual void OnConnect() { }
protected virtual void OnDisconnect() { }
// constructor
//public Connection()
//{ }
public Connection(uint pID, float TO)
{
this.protocolID = pID;
this.timeout = TO;
mode = Mode.None;
running = false;
ClearData();
}
public bool Start(ushort port)
{
Debug.Log("start connection on port " + port);
if (!socket.Open(port))
{
return false;
}
running = true;
OnStart();
return true;
}
public void Stop()
{
Debug.Log("stop connection");
bool connected = IsConnected();
ClearData();
socket.Close();
running = false;
if (connected)
OnDisconnect();
OnStop();
}
public bool IsRunning()
{
return running;
}
public void Listen()
{
Debug.Log("server listening for connection");
bool connected = IsConnected();
ClearData();
if (connected)
OnDisconnect();
mode = Mode.Server;
state = State.Listening;
}
public void Connect(ref System.Net.IPEndPoint addr)
{
//print("client connecting to %hhu.%hhu.%hhu.%hhu:%d\n",
// addr.GetA(), addr.GetB(), addr.GetC(), addr.GetD(), addr.GetPort());
bool connected = IsConnected();
ClearData();
if (connected)
OnDisconnect();
mode = Mode.Client;
state = State.Connecting;
address = addr;
Debug.Log("(0)address = " + address.ToString());
}
public bool IsConnecting()
{
return state == State.Connecting;
}
public bool ConnectFailed()
{
return state == State.ConnectFail;
}
public bool IsConnected()
{
return state == State.Connected;
}
public bool IsListening()
{
return state == State.Listening;
}
public Mode GetMode()
{
return mode;
}
public virtual void Update(float deltaTime)
{
timeoutAccumulator += deltaTime;
if (timeoutAccumulator > timeout)
{
if (state == State.Connecting)
{
Debug.Log("connect timed out");
ClearData();
state = State.ConnectFail;
OnDisconnect();
}
else if (state == State.Connected)
{
Debug.Log("connnection timed out");
ClearData();
if (state == State.Connecting)
{
state = State.ConnectFail;
}
OnDisconnect();
}
}
}
public static string ByteArrayToString(byte[] ba)
{
string hex = System.BitConverter.ToString(ba);
return hex.Replace("-", "");
}
public virtual bool SendPacket(byte[] data, int size)
{
//if (address.GetAddress() == 0)
//{
// return false;
//}
byte[] packet = new byte[size + 4];
packet[0] = (byte)(protocolID >> 24);
packet[1] = (byte)((protocolID >> 16) & 0xff);
packet[2] = (byte)((protocolID >> 8) & 0xff);
packet[3] = (byte)(protocolID & 0xff);
System.Buffer.BlockCopy(data, 0, packet, 4, data.Length);
Debug.Log(ByteArrayToString(packet));
Debug.Log("IP = " + address.ToString());
return socket.Send(ref address, packet, size + 4);
}
public virtual int ReceivePacket(ref byte[] data, int size)
{
byte[] packet = new byte[size + 4];
System.Net.IPEndPoint remoteIpEp = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
System.Net.EndPoint remoteEp = (System.Net.EndPoint)remoteIpEp;
int count = socket.Receive(ref remoteEp, packet, size + 4);
if (count == 0)
{
return 0;
}
if (count <= 4)
{
return 0;
}
if (packet[0] != (byte)(protocolID >> 24) ||
packet[1] != (byte)((protocolID >> 16) & 0xFF) ||
packet[2] != (byte)((protocolID >> 8) & 0xFF) ||
packet[3] != (byte)(protocolID & 0xFF))
{
return 0;
}
if (mode == Mode.Server && !IsConnected())
{
Debug.Log("server accepts connection from client ");
state = State.Connected;
address = remoteIpEp;
OnConnect();
}
// TODO
if (address.Equals(remoteIpEp))
{
if (state == State.Connecting)
{
state = State.Connected;
OnConnect();
}
timeoutAccumulator = 0.0f;
System.Buffer.BlockCopy(packet, 4, data, 0, count - 4);
return count - 4;
}
return 0;
}
public virtual int GetHeaderSize()
{
return 4;
}
}
public struct PacketData
{
public uint sequence;
public int size;
public float time;
}
public class PacketQueue : LinkedList<PacketData>
{
bool sequence_more_recent(uint s1, uint s2, uint max_sequence)
{
return ((s1 > s2) && (s1 - s2 <= max_sequence / 2)) || ((s2 > s1) && (s2 - s1 > max_sequence / 2));
}
public bool exists(uint sequence)
{
foreach (PacketData pd in this)
{
if (pd.sequence == sequence)
{
return true;
}
}
return false;
}
public void insert_sorted(PacketData p, uint max_sequence)
{
if (this.Count == 0)
{
this.AddLast(p);
}
else
{
if (!sequence_more_recent(p.sequence, this.First.Value.sequence, max_sequence))
{
this.AddFirst(p);
}
else if (sequence_more_recent(p.sequence, this.Last.Value.sequence, max_sequence))
{
this.AddLast(p);
}
else
{
for (LinkedListNode<PacketData> node = this.First; node != this.Last.Next; node = node.Next)
{
if (sequence_more_recent(node.Value.sequence, p.sequence, max_sequence))
{
this.AddAfter(node, p);
break;
}
}
}
}
}
public void verify_sorted(uint max_sequence)
{
if (this.Count < 2)
{
Debug.LogError("queue is too short");
}
for (LinkedListNode<PacketData> node = this.First; node != this.Last.Next; node = node.Next)
{
if (node.Next != null)
{
if (sequence_more_recent(node.Value.sequence, node.Next.Value.sequence, max_sequence))
{
Debug.LogError("verify_sorted fail!");
}
}
}
}
}
public class ReliabilitySystem
{
public ReliabilitySystem(uint max_sequence = 0xffffffff)
{
this.max_sequence = max_sequence;
Reset();
}
public void Reset()
{
local_sequence = 0;
remote_sequence = 0;
sentQueue.Clear();
receivedQueue.Clear();
pendingAckQueue.Clear();
ackedQueue.Clear();
sent_packets = 0;
recv_packets = 0;
lost_packets = 0;
acked_packets = 0;
sent_bandwidth = 0.0f;
acked_bandwidth = 0.0f;
rtt = 0.0f;
rtt_maximum = 0.0f;
}
public void PacketSent(int size)
{
if (sentQueue.exists(local_sequence))
{
Debug.Log("local sequence exists " + local_sequence);
}
PacketData data;
data.sequence = local_sequence;
data.size = size;
data.time = 0.0f;
sentQueue.AddLast(data);
pendingAckQueue.AddLast(data);
sent_packets++;
local_sequence++;
if (local_sequence > max_sequence)
{
local_sequence = 0;
}
}
static bool sequence_more_recent(uint s1, uint s2, uint max_sequence)
{
return ((s1 > s2) && (s1 - s2 <= max_sequence / 2)) || ((s2 > s1) && (s2 - s1 > max_sequence / 2));
}
public void PacketReceived(uint sequence, int size)
{
recv_packets++;
if (receivedQueue.exists(sequence))
return;
PacketData data;
data.sequence = sequence;
data.size = size;
data.time = 0.0f;
receivedQueue.AddLast(data);
if (sequence_more_recent(sequence, remote_sequence, max_sequence))
{
remote_sequence = sequence;
}
}
public uint GenerateAckBits()
{
return generate_ack_bits(GetRemoteSequence(), ref receivedQueue, max_sequence);
}
public void ProcessAck(uint ack, uint ack_bits)
{
process_ack(ack, ack_bits, ref pendingAckQueue, ref ackedQueue, ref acks, acked_packets, rtt, max_sequence);
}
public void Update(float deltaTime)
{
acks.Clear();
AdvanceQueueTime(deltaTime);
UpdateQueues();
UpdateStatus();
}
public static uint bit_index_for_sequence(uint sequence, uint ack, uint max_sequence)
{
if (sequence > ack)
{
return ack + (max_sequence - sequence);
}
else
{
return ack - 1 - sequence;
}
}
public static uint generate_ack_bits(uint ack, ref PacketQueue received_queue, uint max_sequence)
{
uint ack_bits = 0;
foreach (PacketData received in received_queue)
{
if (received.sequence == ack || sequence_more_recent(received.sequence, ack, max_sequence))
break;
uint bit_index = bit_index_for_sequence(received.sequence, ack, max_sequence);
if (bit_index <= 31)
{
ack_bits |= 1U << (int)bit_index;
}
}
return ack_bits;
}
public static void process_ack(uint ack, uint ack_bits, ref PacketQueue pending_ack_queue,
ref PacketQueue acked_queue, ref List<uint> acks,
uint acked_packets, float rtt, uint max_sequence)
{
if (pending_ack_queue.Count == 0)
{
return;
}
var node = pending_ack_queue.First;
while (node != null)
{
var nextnode = node.Next;
bool acked = false;
if (node.Value.sequence == ack)
{
acked = true;
}
else if (!sequence_more_recent(node.Value.sequence, ack, max_sequence))
{
uint bit_index = bit_index_for_sequence(node.Value.sequence, ack, max_sequence);
if (bit_index <= 31)
{
acked = System.Convert.ToBoolean((ack_bits >> (int)bit_index) & 1);
}
}
if (acked)
{
rtt += (node.Value.time - rtt) * 0.1f;
acked_queue.insert_sorted(node.Value, max_sequence);
acks.Add(node.Value.sequence);
acked_packets++;
pending_ack_queue.Remove(node);
node = nextnode;
}
else
{
node = nextnode;
}
}
}
public uint GetLocalSequence()
{
return local_sequence;
}
public uint GetRemoteSequence()
{
return remote_sequence;
}
public uint GetMaxSequence()
{
return max_sequence;
}
public void GetAcks()
{
}
public uint GetSentPackets()
{
return sent_packets;
}
public uint GetReceivePackets()
{
return recv_packets;
}
public uint GetLostPackets()
{
return lost_packets;
}
public uint GetAckedPackets()
{
return acked_packets;
}
public float GetSentBandwidth()
{
return sent_bandwidth;
}
public float GetAckedBandwidth()
{
return acked_bandwidth;
}
public float GetRoundTripTime()
{
return rtt;
}
public int GetHeaderSize()
{
return 12;
}
protected void AdvanceQueueTime(float deltaTime)
{
PacketData data;
for (LinkedListNode<PacketData> node = sentQueue.First; node != sentQueue.Last.Next; node = node.Next)
{
data.sequence = node.Value.sequence;
data.size = node.Value.size;
data.time = node.Value.time + deltaTime;
node.Value = data;
}
for (LinkedListNode<PacketData> node = receivedQueue.First; node != receivedQueue.Last.Next; node = node.Next)
{
data.sequence = node.Value.sequence;
data.size = node.Value.size;
data.time = node.Value.time + deltaTime;
node.Value = data;
}
for (LinkedListNode<PacketData> node = pendingAckQueue.First; node != pendingAckQueue.Last.Next; node = node.Next)
{
data.sequence = node.Value.sequence;
data.size = node.Value.size;
data.time = node.Value.time + deltaTime;
node.Value = data;
}
for (LinkedListNode<PacketData> node = ackedQueue.First; node != ackedQueue.Last.Next; node = node.Next)
{
data.sequence = node.Value.sequence;
data.size = node.Value.size;
data.time = node.Value.time + deltaTime;
node.Value = data;
}
}
protected void UpdateQueues()
{
const float epsilon = 0.001f;
while ((sentQueue.Count > 0) && (sentQueue.First.Value.time > (rtt_maximum + epsilon)))
{
sentQueue.RemoveFirst();
}
if (receivedQueue.Count > 0)
{
uint latest_sequence = receivedQueue.Last.Value.sequence;
uint minimum_sequence = latest_sequence >= 34 ? (latest_sequence - 34) : max_sequence - (34 - latest_sequence);
while ((receivedQueue.Count > 0) && !sequence_more_recent(receivedQueue.First.Value.sequence, minimum_sequence, max_sequence))
{
receivedQueue.RemoveFirst();
}
}
while (ackedQueue.Count > 0 && ackedQueue.First.Value.time > rtt_maximum * 2 - epsilon)
{
ackedQueue.RemoveFirst();
}
while (pendingAckQueue.Count > 0 && pendingAckQueue.First.Value.time > rtt_maximum + epsilon)
{
pendingAckQueue.RemoveFirst();
lost_packets++;
}
}
protected void UpdateStatus()
{
int sent_bytes_per_second = 0;
foreach (PacketData data in sentQueue)
{
sent_bytes_per_second += data.size;
}
int acked_packets_per_second = 0;
int acked_bytes_per_second = 0;
foreach (PacketData data in ackedQueue)
{
if (data.time >= rtt_maximum)
{
acked_packets_per_second++;
acked_bytes_per_second += data.size;
}
}
sent_bytes_per_second = (int)(sent_bytes_per_second / rtt_maximum);
acked_bytes_per_second = (int)(acked_bytes_per_second / rtt_maximum);
sent_bandwidth = sent_bytes_per_second * (8 / 1000.0f);
acked_bandwidth = acked_bytes_per_second * (8 / 1000.0f);
}
uint max_sequence;
uint local_sequence;
uint remote_sequence;
uint sent_packets;
uint recv_packets;
uint lost_packets;
uint acked_packets;
float sent_bandwidth;
float acked_bandwidth;
float rtt;
float rtt_maximum;
List<uint> acks;
PacketQueue sentQueue = new PacketQueue();
PacketQueue pendingAckQueue = new PacketQueue();
PacketQueue receivedQueue = new PacketQueue();
PacketQueue ackedQueue = new PacketQueue();
}
public class ReliableConnection : Connection
{
public ReliableConnection(uint protocolId, float timeout, uint max_sequence = 0xffffffff)
: base(protocolId, timeout)
{
reliabilitySystem = new ReliabilitySystem(max_sequence);
ClearData();
}
~ReliableConnection()
{
if (base.IsRunning())
{
base.Stop();
}
}
bool SendPacket(ref byte[] data, int size)
{
const int header = 12;
byte[] packet = new byte[header + size];
uint seq = reliabilitySystem.GetLocalSequence();
uint ack = reliabilitySystem.GetRemoteSequence();
uint ack_bits = reliabilitySystem.GenerateAckBits();
WriteHeader(ref packet, seq, ack, ack_bits);
System.Buffer.BlockCopy(data, 0, packet, header, data.Length);
if (!base.SendPacket(packet, size + header))
{
return false;
}
reliabilitySystem.PacketSent(size);
return true;
}
public override int ReceivePacket(ref byte[] data, int size)
{
const int header = 12;
if (size <= header)
{
return 0;
}
byte[] packet = new byte[header + size];
int count = base.ReceivePacket(ref packet, size + header);
if (count == 0)
return 0;
if (count <= header)
return 0;
uint packet_sequence = 0;
uint packet_ack = 0;
uint packet_ack_bits = 0;
ReadHeader(ref packet, ref packet_sequence, ref packet_ack, ref packet_ack_bits);
reliabilitySystem.PacketReceived(packet_sequence, count - header);
reliabilitySystem.ProcessAck(packet_ack, packet_ack_bits);
System.Buffer.BlockCopy(packet, header, data, 0, count - header);
return count - header;
}
public void WriteInteger(ref byte[] data, uint value, int offset)
{
data[offset] = (byte)(value >> 24);
data[offset + 1] = (byte)((value >> 16) & 0xff);
data[offset + 2] = (byte)((value >> 8) & 0xff);
data[offset + 3] = (byte)(value & 0xff);
}
public void WriteHeader(ref byte[] header, uint sequence, uint ack, uint ack_bits)
{
WriteInteger(ref header, sequence, 0);
WriteInteger(ref header, ack, 4);
WriteInteger(ref header, ack_bits, 8);
}
public void ReadInteger(ref byte[] data, ref uint value, int offset)
{
value = ((uint)(data[offset] << 24) |
(uint)(data[offset + 1] << 16) |
(uint)(data[offset + 2] << 8) |
(uint)(data[offset + 3]));
}
public void ReadHeader(ref byte[] header, ref uint sequence, ref uint ack, ref uint ack_bits)
{
ReadInteger(ref header, ref sequence, 0);
ReadInteger(ref header, ref ack, 4);
ReadInteger(ref header, ref ack_bits, 8);
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
reliabilitySystem.Update(deltaTime);
}
public override int GetHeaderSize()
{
return base.GetHeaderSize() + reliabilitySystem.GetHeaderSize();
}
public ReliabilitySystem GetReliableSystem()
{
return reliabilitySystem;
}
protected override void OnStop()
{
ClearData();
}
protected override void OnDisconnect()
{
ClearData();
}
void ClearData()
{
reliabilitySystem.Reset();
}
ReliabilitySystem reliabilitySystem;
}