Skip to content

Commit

Permalink
修复空引用错误 #20
Browse files Browse the repository at this point in the history
  • Loading branch information
KumoKyaku committed Aug 17, 2022
1 parent ee85b66 commit d31308b
Showing 1 changed file with 43 additions and 38 deletions.
81 changes: 43 additions & 38 deletions KCP/Kcp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,30 +54,36 @@ internal protected override BufferOwner CreateBuffer(int needSize)
return res;
}

/// <summary>
/// TryRecv Recv设计上同一实际只允许一个线程调用。
/// 因为要保证数据顺序,多个线程同时调用Recv也没有意义。
/// 所以只需要部分加锁即可。
/// </summary>
/// <returns></returns>
public (BufferOwner buffer, int avalidLength) TryRecv()
{
if (rcv_queue.Count == 0)
var peekSize = -1;
lock (rcv_queueLock)
{
///没有可用包
return (null, -1);
}
if (rcv_queue.Count == 0)
{
///没有可用包
return (null, -1);
}

var peekSize = -1;
var seq = rcv_queue[0];
var seq = rcv_queue[0];

if (seq.frg == 0)
{
peekSize = (int)seq.len;
}
if (seq.frg == 0)
{
peekSize = (int)seq.len;
}

if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return (null, -1);
}
if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return (null, -1);
}

lock (rcv_queueLock)
{
uint length = 0;

foreach (var item in rcv_queue)
Expand All @@ -90,11 +96,11 @@ internal protected override BufferOwner CreateBuffer(int needSize)
}

peekSize = (int)length;
}

if (peekSize <= 0)
{
return (null, -2);
if (peekSize <= 0)
{
return (null, -2);
}
}

var buffer = CreateBuffer(peekSize);
Expand Down Expand Up @@ -194,28 +200,27 @@ int UncheckRecv(Span<byte> buffer)
/// <returns></returns>
public int PeekSize()
{

if (rcv_queue.Count == 0)
lock (rcv_queueLock)
{
///没有可用包
return -1;
}
if (rcv_queue.Count == 0)
{
///没有可用包
return -1;
}

var seq = rcv_queue[0];
var seq = rcv_queue[0];

if (seq.frg == 0)
{
return (int)seq.len;
}
if (seq.frg == 0)
{
return (int)seq.len;
}

if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return -1;
}
if (rcv_queue.Count < seq.frg + 1)
{
///没有足够的包
return -1;
}

lock (rcv_queueLock)
{
uint length = 0;

foreach (var item in rcv_queue)
Expand Down

0 comments on commit d31308b

Please sign in to comment.