/
Kcp.cs
1600 lines (1384 loc) · 46.6 KB
/
Kcp.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
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using static System.Math;
using BufferOwner = System.Buffers.IMemoryOwner<byte>;
namespace System.Net.Sockets.Kcp
{
/// <summary>
/// https://github.com/skywind3000/kcp/wiki/Network-Layer
/// <para>外部buffer ----拆分拷贝----等待列表 -----移动----发送列表----拷贝----发送buffer---output</para>
/// https://github.com/skywind3000/kcp/issues/118#issuecomment-338133930
/// </summary>
public partial class Kcp : IKcpSetting, IKcpUpdate, IDisposable
{
/// 为了减少阅读难度,变量名尽量于 C版 统一
/*
conv 会话ID
mtu 最大传输单元
mss 最大分片大小
state 连接状态(0xFFFFFFFF表示断开连接)
snd_una 第一个未确认的包
snd_nxt 待发送包的序号
rcv_nxt 待接收消息序号
ssthresh 拥塞窗口阈值
rx_rttvar ack接收rtt浮动值
rx_srtt ack接收rtt静态值
rx_rto 由ack接收延迟计算出来的复原时间
rx_minrto 最小复原时间
snd_wnd 发送窗口大小
rcv_wnd 接收窗口大小
rmt_wnd, 远端接收窗口大小
cwnd, 拥塞窗口大小
probe 探查变量,IKCP_ASK_TELL表示告知远端窗口大小。IKCP_ASK_SEND表示请求远端告知窗口大小
interval 内部flush刷新间隔
ts_flush 下次flush刷新时间戳
nodelay 是否启动无延迟模式
updated 是否调用过update函数的标识
ts_probe, 下次探查窗口的时间戳
probe_wait 探查窗口需要等待的时间
dead_link 最大重传次数
incr 可发送的最大数据量
fastresend 触发快速重传的重复ack个数
nocwnd 取消拥塞控制
stream 是否采用流传输模式
snd_queue 发送消息的队列
rcv_queue 接收消息的队列
snd_buf 发送消息的缓存
rcv_buf 接收消息的缓存
acklist 待发送的ack列表
buffer 存储消息字节流的内存
output udp发送消息的回调函数
*/
/// <summary>
/// create a new kcp control object, 'conv' must equal in two endpoint
/// from the same connection.
/// </summary>
/// <param name="conv_"></param>
/// <param name="output_"></param>
public Kcp(uint conv_, IKcpCallback callback)
{
conv = conv_;
callbackHandle = callback;
snd_wnd = IKCP_WND_SND;
rcv_wnd = IKCP_WND_RCV;
rmt_wnd = IKCP_WND_RCV;
mtu = IKCP_MTU_DEF;
mss = mtu - IKCP_OVERHEAD;
buffer = CreateBuffer(BufferNeedSize);
rx_rto = IKCP_RTO_DEF;
rx_minrto = IKCP_RTO_MIN;
interval = IKCP_INTERVAL;
ts_flush = IKCP_INTERVAL;
ssthresh = IKCP_THRESH_INIT;
dead_link = IKCP_DEADLINK;
}
#region Const
public const int IKCP_RTO_NDL = 30; // no delay min rto
public const int IKCP_RTO_MIN = 100; // normal min rto
public const int IKCP_RTO_DEF = 200;
public const int IKCP_RTO_MAX = 60000;
public const int IKCP_CMD_PUSH = 81; // cmd: push data
public const int IKCP_CMD_ACK = 82; // cmd: ack
public const int IKCP_CMD_WASK = 83; // cmd: window probe (ask)
public const int IKCP_CMD_WINS = 84; // cmd: window size (tell)
public const int IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK
public const int IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS
public const int IKCP_WND_SND = 32;
public const int IKCP_WND_RCV = 128; // must >= max fragment size
public const int IKCP_MTU_DEF = 1400;
public const int IKCP_ACK_FAST = 3;
public const int IKCP_INTERVAL = 100;
public const int IKCP_OVERHEAD = 24;
public const int IKCP_DEADLINK = 20;
public const int IKCP_THRESH_INIT = 2;
public const int IKCP_THRESH_MIN = 2;
public const int IKCP_PROBE_INIT = 7000; // 7 secs to probe window size
public const int IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window
#endregion
#region kcp members
/// <summary>
/// 频道号
/// </summary>
public uint conv { get; protected set; }
/// <summary>
/// 最大传输单元(Maximum Transmission Unit,MTU)
/// </summary>
uint mtu;
/// <summary>
/// 缓冲区最小大小
/// </summary>
int BufferNeedSize
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return (int)((mtu/* + IKCP_OVERHEAD*/) /** 3*/);
}
}
/// <summary>
/// 最大报文段长度
/// </summary>
uint mss;
int state;
uint snd_una;
uint snd_nxt;
/// <summary>
/// 下一个等待接收消息ID
/// </summary>
uint rcv_nxt;
uint ts_recent;
uint ts_lastack;
uint ssthresh;
uint rx_rttval;
uint rx_srtt;
uint rx_rto;
uint rx_minrto;
uint snd_wnd;
uint rcv_wnd;
uint rmt_wnd;
uint cwnd;
uint probe;
uint current;
uint interval;
uint ts_flush;
uint xmit;
uint nodelay;
uint updated;
uint ts_probe;
uint probe_wait;
uint dead_link;
uint incr;
int fastresend;
int nocwnd;
int logmask;
public int stream;
BufferOwner buffer;
/// <summary>
/// <para>https://github.com/skywind3000/kcp/issues/53</para>
/// 按照 C版 设计,使用小端字节序
/// </summary>
public static bool IsLittleEndian = true;
#endregion
private readonly object snd_bufLock = new object();
private readonly object rcv_queueLock = new object();
private readonly object rcv_bufLock = new object();
/// <summary>
/// 发送 ack 队列
/// </summary>
ConcurrentQueue<(uint sn, uint ts)> acklist = new ConcurrentQueue<(uint sn, uint ts)>();
/// <summary>
/// 发送等待队列
/// </summary>
ConcurrentQueue<KcpSegment> snd_queue = new ConcurrentQueue<KcpSegment>();
/// <summary>
/// 正在发送列表
/// </summary>
LinkedList<KcpSegment> snd_buf = new LinkedList<KcpSegment>();
/// <summary>
/// 正在等待触发接收回调函数消息列表
/// <para>需要执行的操作 添加 遍历 删除</para>
/// </summary>
List<KcpSegment> rcv_queue = new List<KcpSegment>();
/// <summary>
/// 正在等待重组消息列表
/// <para>需要执行的操作 添加 插入 遍历 删除</para>
/// </summary>
LinkedList<KcpSegment> rcv_buf = new LinkedList<KcpSegment>();
#region IDisposable Support
private bool disposedValue = false; // 要检测冗余调用
/// <summary>
/// 是否正在释放
/// </summary>
private bool m_disposing = false;
protected bool CheckDispose()
{
if (m_disposing)
{
return true;
}
if (disposedValue)
{
throw new ObjectDisposedException(
$"{nameof(Kcp)} [conv:{conv}]");
}
return false;
}
protected virtual void Dispose(bool disposing)
{
try
{
m_disposing = true;
if (!disposedValue)
{
if (disposing)
{
// 释放托管状态(托管对象)。
callbackHandle = null;
acklist = null;
buffer = null;
}
// 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// 将大型字段设置为 null。
void FreeCollection(IEnumerable<KcpSegment> collection)
{
if (collection == null)
{
return;
}
foreach (var item in collection)
{
try
{
KcpSegment.FreeHGlobal(item);
}
catch (Exception)
{
//理论上此处不会有任何异常
}
}
}
while (snd_queue != null &&
(snd_queue.TryDequeue(out var segment)
|| !snd_queue.IsEmpty)
)
{
try
{
KcpSegment.FreeHGlobal(segment);
}
catch (Exception)
{
//理论上这里没有任何异常;
}
}
snd_queue = null;
lock (snd_bufLock)
{
FreeCollection(snd_buf);
snd_buf?.Clear();
snd_buf = null;
}
lock (rcv_bufLock)
{
FreeCollection(rcv_buf);
rcv_buf?.Clear();
rcv_buf = null;
}
lock (rcv_queueLock)
{
FreeCollection(rcv_queue);
rcv_queue?.Clear();
rcv_queue = null;
}
disposedValue = true;
}
}
finally
{
m_disposing = false;
}
}
// 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
~Kcp()
{
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(false);
}
// 添加此代码以正确实现可处置模式。
/// <summary>
/// 释放不是严格线程安全的,尽量使用和Update相同的线程调用,
/// 或者等待析构时自动释放。
/// </summary>
public void Dispose()
{
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// 如果在以上内容中替代了终结器,则取消注释以下行。
GC.SuppressFinalize(this);
}
#endregion
}
//extension 重构和新增加的部分
public partial class Kcp
{
IKcpCallback callbackHandle;
/// <summary>
/// 如果外部能够提供缓冲区则使用外部缓冲区,否则new byte[]
/// </summary>
/// <param name="needSize"></param>
/// <returns></returns>
internal protected BufferOwner CreateBuffer(int needSize)
{
var res = callbackHandle?.RentBuffer(needSize);
if (res == null)
{
return new KcpInnerBuffer(needSize);
}
else
{
if (res.Memory.Length < needSize)
{
throw new ArgumentException($"{nameof(callbackHandle.RentBuffer)} 指定的委托不符合标准,返回的" +
$"BufferOwner.Memory.Length 小于 {nameof(needSize)}");
}
}
return res;
}
internal protected class KcpInnerBuffer : BufferOwner
{
private readonly Memory<byte> _memory;
public Memory<byte> Memory
{
get
{
if (alreadyDisposed)
{
throw new ObjectDisposedException(nameof(KcpInnerBuffer));
}
return _memory;
}
}
public KcpInnerBuffer(int size)
{
_memory = new Memory<byte>(new byte[size]);
}
bool alreadyDisposed = false;
public void Dispose()
{
alreadyDisposed = true;
}
}
public (BufferOwner buffer, int avalidLength) TryRecv()
{
if (rcv_queue.Count == 0)
{
///没有可用包
return (null, -1);
}
var peekSize = -1;
var seq = rcv_queue[0];
if (seq.frg == 0)
{
peekSize = (int)seq.len;
}
if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return (null, -1);
}
lock (rcv_queueLock)
{
uint length = 0;
foreach (var item in rcv_queue)
{
length += item.len;
if (item.frg == 0)
{
break;
}
}
peekSize = (int)length;
}
if (peekSize <= 0)
{
return (null, -2);
}
var buffer = CreateBuffer(peekSize);
var recvlength = UncheckRecv(buffer.Memory.Span);
return (buffer, recvlength);
}
}
public partial class Kcp
{
static uint Ibound(uint lower, uint middle, uint upper)
{
return Min(Max(lower, middle), upper);
}
static int Itimediff(uint later, uint earlier)
{
return ((int)(later - earlier));
}
/// <summary>
/// user/upper level recv: returns size, returns below zero for EAGAIN
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public int Recv(Span<byte> buffer)
{
if (0 == rcv_queue.Count)
{
return -1;
}
var peekSize = PeekSize();
if (peekSize < 0)
{
return -2;
}
if (peekSize > buffer.Length)
{
return -3;
}
/// 拆分函数
var recvLength = UncheckRecv(buffer);
return recvLength;
}
/// <summary>
/// 这个函数不检查任何参数
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
int UncheckRecv(Span<byte> buffer)
{
var recover = false;
if (rcv_queue.Count >= rcv_wnd)
{
recover = true;
}
#region merge fragment.
/// merge fragment.
var recvLength = 0;
lock (rcv_queueLock)
{
var count = 0;
foreach (var seg in rcv_queue)
{
seg.data.CopyTo(buffer.Slice(recvLength));
recvLength += (int)seg.len;
count++;
int frg = seg.frg;
KcpSegment.FreeHGlobal(seg);
if (frg == 0)
{
break;
}
}
if (count > 0)
{
rcv_queue.RemoveRange(0, count);
}
}
#endregion
Move_Rcv_buf_2_Rcv_queue();
#region fast recover
/// fast recover
if (rcv_queue.Count < rcv_wnd && recover)
{
// ready to send back IKCP_CMD_WINS in ikcp_flush
// tell remote my window size
probe |= IKCP_ASK_TELL;
}
#endregion
return recvLength;
}
/// <summary>
/// move available data from rcv_buf -> rcv_queue
/// </summary>
void Move_Rcv_buf_2_Rcv_queue()
{
lock (rcv_bufLock)
{
while (rcv_buf.Count > 0)
{
var seg = rcv_buf.First.Value;
if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd)
{
rcv_buf.RemoveFirst();
lock (rcv_queueLock)
{
rcv_queue.Add(seg);
}
rcv_nxt++;
}
else
{
break;
}
}
}
}
/// <summary>
/// check the size of next message in the recv queue
/// </summary>
/// <returns></returns>
public int PeekSize()
{
if (rcv_queue.Count == 0)
{
///没有可用包
return -1;
}
var seq = rcv_queue[0];
if (seq.frg == 0)
{
return (int)seq.len;
}
if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return -1;
}
lock (rcv_queueLock)
{
uint length = 0;
foreach (var item in rcv_queue)
{
length += item.len;
if (item.frg == 0)
{
break;
}
}
return (int)length;
}
}
/// <summary>
/// user/upper level send, returns below zero for error
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public int Send(Span<byte> buffer)
{
if (CheckDispose())
{
//检查释放
return -4;
}
if (mss <= 0)
{
throw new InvalidOperationException($" mss <= 0 ");
}
if (buffer.Length == 0)
{
return -1;
}
var offset = 0;
var count = 0;
#region append to previous segment in streaming mode (if possible)
/// 基于线程安全和数据结构的等原因,移除了追加数据到最后一个包行为。
#endregion
#region fragment
if (buffer.Length <= mss)
{
count = 1;
}
else
{
count = (int)(buffer.Length + mss - 1) / (int)mss;
}
if (count > IKCP_WND_RCV)
{
return -2;
}
if (count == 0)
{
count = 1;
}
for (var i = 0; i < count; i++)
{
var size = 0;
if (buffer.Length - offset > mss)
{
size = (int)mss;
}
else
{
size = buffer.Length - offset;
}
var seg = KcpSegment.AllocHGlobal(size);
buffer.Slice(offset, size).CopyTo(seg.data);
offset += size;
seg.frg = (byte)(count - i - 1);
snd_queue.Enqueue(seg);
}
#endregion
return 0;
}
/// <summary>
/// update ack.
/// </summary>
/// <param name="rtt"></param>
void Update_ack(int rtt)
{
if (rx_srtt == 0)
{
rx_srtt = (uint)rtt;
rx_rttval = (uint)rtt / 2;
}
else
{
int delta = (int)((uint)rtt - rx_srtt);
if (delta < 0)
{
delta = -delta;
}
rx_rttval = (3 * rx_rttval + (uint)delta) / 4;
rx_srtt = (uint)((7 * rx_srtt + rtt) / 8);
if (rx_srtt < 1)
{
rx_srtt = 1;
}
}
var rto = rx_srtt + Max(interval, 4 * rx_rttval);
rx_rto = Ibound(rx_minrto, rto, IKCP_RTO_MAX);
}
void Shrink_buf()
{
lock (snd_bufLock)
{
snd_una = snd_buf.Count > 0 ? snd_buf.First.Value.sn : snd_nxt;
}
}
void Parse_ack(uint sn)
{
if (Itimediff(sn, snd_una) < 0 || Itimediff(sn, snd_nxt) >= 0)
{
return;
}
lock (snd_bufLock)
{
for (var p = snd_buf.First; p != null; p = p.Next)
{
var seg = p.Value;
if (sn == seg.sn)
{
snd_buf.Remove(p);
KcpSegment.FreeHGlobal(seg);
break;
}
if (Itimediff(sn, seg.sn) < 0)
{
break;
}
}
}
}
void Parse_una(uint una)
{
/// 删除给定时间之前的片段。保留之后的片段
lock (snd_bufLock)
{
while (snd_buf.First != null)
{
var seg = snd_buf.First.Value;
if (Itimediff(una, seg.sn) > 0)
{
KcpSegment.FreeHGlobal(seg);
snd_buf.RemoveFirst();
}
else
{
break;
}
}
}
}
void Parse_fastack(uint sn)
{
if (Itimediff(sn, snd_una) < 0 || Itimediff(sn, snd_nxt) >= 0)
{
return;
}
lock (snd_bufLock)
{
foreach (var item in snd_buf)
{
var seg = item;
if (Itimediff(sn, seg.sn) < 0)
{
break;
}
else if (sn != seg.sn)
{
seg.fastack++;
}
}
}
}
void Parse_data(KcpSegment newseg)
{
var sn = newseg.sn;
lock (rcv_bufLock)
{
if (Itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || Itimediff(sn, rcv_nxt) < 0)
{
KcpSegment.FreeHGlobal(newseg);
return;
}
var repeat = false;
///检查是否重复消息和插入位置
LinkedListNode<KcpSegment> p;
for (p = rcv_buf.Last; p != null; p = p.Previous)
{
var seg = p.Value;
if (seg.sn == sn)
{
repeat = true;
break;
}
if (Itimediff(sn, seg.sn) > 0)
{
break;
}
}
if (!repeat)
{
if (p == null)
{
rcv_buf.AddFirst(newseg);
}
else
{
rcv_buf.AddAfter(p, newseg);
}
}
else
{
KcpSegment.FreeHGlobal(newseg);
}
}
Move_Rcv_buf_2_Rcv_queue();
}
/// <summary>
/// when you received a low level packet (eg. UDP packet), call it
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public int Input(Span<byte> data)
{
if (CheckDispose())
{
//检查释放
return -4;
}
uint temp_una = snd_una;
if (data.Length < IKCP_OVERHEAD)
{
return -1;
}
var offset = 0;
int flag = 0;
uint maxack = 0;
while (true)
{
uint ts = 0;
uint sn = 0;
uint length = 0;
uint una = 0;
uint conv_ = 0;
ushort wnd = 0;
byte cmd = 0;
byte frg = 0;
if (data.Length - offset < IKCP_OVERHEAD)
{
break;
}
if (IsLittleEndian)
{
conv_ = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset));
offset += 4;
if (conv != conv_)
{
return -1;
}
cmd = data[offset];
offset += 1;
frg = data[offset];
offset += 1;
wnd = BinaryPrimitives.ReadUInt16LittleEndian(data.Slice(offset));
offset += 2;
ts = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset));
offset += 4;
sn = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset));
offset += 4;
una = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset));
offset += 4;
length = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset));
offset += 4;
}
else
{
conv_ = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset));
offset += 4;
if (conv != conv_)
{
return -1;
}
cmd = data[offset];
offset += 1;
frg = data[offset];
offset += 1;
wnd = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset));
offset += 2;
ts = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset));
offset += 4;
sn = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset));
offset += 4;
una = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset));
offset += 4;
length = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset));
offset += 4;
}
if (data.Length - offset < length || (int)length < 0)
{
return -2;
}
switch (cmd)
{
case IKCP_CMD_PUSH:
case IKCP_CMD_ACK:
case IKCP_CMD_WASK:
case IKCP_CMD_WINS:
break;
default:
return -3;
}
rmt_wnd = wnd;
Parse_una(una);
Shrink_buf();
if (IKCP_CMD_ACK == cmd)
{
if (Itimediff(current, ts) >= 0)
{
Update_ack(Itimediff(current, ts));
}
Parse_ack(sn);
Shrink_buf();
if (flag == 0)
{
flag = 1;
maxack = sn;
}
else if (Itimediff(sn, maxack) > 0)
{
maxack = sn;
}
}
else if (IKCP_CMD_PUSH == cmd)
{
if (Itimediff(sn, rcv_nxt + rcv_wnd) < 0)
{
///instead of ikcp_ack_push
acklist.Enqueue((sn, ts));
if (Itimediff(sn, rcv_nxt) >= 0)
{
var seg = KcpSegment.AllocHGlobal((int)length);
seg.conv = conv_;
seg.cmd = cmd;
seg.frg = frg;
seg.wnd = wnd;
seg.ts = ts;
seg.sn = sn;