Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,40 @@ public override async Task ReceiveAsync(Memory<byte> data)
// 处理上次粘包数据
data = ConcatBuffer(data);

// 拷贝数据
var len = length - _receivedLength;
var segment = data.Length > len ? data[..len] : data;
segment.CopyTo(_data[_receivedLength..]);

if (data.Length > len)
while (data.Length > 0)
{
SlicePackage(data, data.Length - len);
}
// 拷贝数据
var len = length - _receivedLength;
var segment = data.Length > len ? data[..len] : data;
segment.CopyTo(_data[_receivedLength..]);

// 更新已接收长度
_receivedLength += segment.Length;
// 更新已接收长度
_receivedLength += segment.Length;

// 如果已接收长度等于总长度则触发回调
if (_receivedLength == length)
{
// 重置已接收长度
_receivedLength = 0;
if (ReceivedCallBack != null)
// 如果已接收长度等于总长度则触发回调
if (_receivedLength == length)
{
// 重置已接收长度
_receivedLength = 0;
if (ReceivedCallBack != null)
{
await ReceivedCallBack(_data);
}
}

// 检查剩余长度是否大于总长度
if (data.Length >= segment.Length + length)
{
data = data[segment.Length..];
continue;
}

// 缓存剩余数据
if (data.Length > len)
{
await ReceivedCallBack(_data);
SlicePackage(data, data.Length - len);
}
break;
}
}
}
22 changes: 15 additions & 7 deletions test/UnitTest/Services/TcpSocketFactoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,14 +249,22 @@ public async Task FixLengthDataPackageHandler_Sticky()

// 验证接收到的数据
Assert.Equal(receivedBuffer.ToArray(), [1, 2, 3, 4, 5, 3, 4]);

// 等待第二次数据
receivedBuffer = Memory<byte>.Empty;
tcs = new TaskCompletionSource();

// 等待第二次数据
await tcs.Task;

// 验证第二次收到的数据
Assert.Equal(receivedBuffer.ToArray(), [1, 2, 3, 4, 5, 6, 7]);
Assert.Equal(receivedBuffer.ToArray(), [2, 2, 3, 4, 5, 6, 7]);
tcs = new TaskCompletionSource();
await tcs.Task;

// 等待第二次数据
await tcs.Task;

// 验证第三次收到的数据
Assert.Equal(receivedBuffer.ToArray(), [3, 2, 3, 4, 5, 6, 7]);

// 关闭连接
client.Close();
Expand Down Expand Up @@ -398,16 +406,16 @@ private static async Task MockStickyPackageAsync(TcpClient client)
await stream.WriteAsync(block, CancellationToken.None);

// 模拟延时
await Task.Delay(50);
await Task.Delay(10);

// 模拟拆包发送第二段数据
await stream.WriteAsync(new byte[] { 0x3, 0x4, 0x1, 0x2 }, CancellationToken.None);
await stream.WriteAsync(new byte[] { 0x3, 0x4, 0x2, 0x2 }, CancellationToken.None);

// 模拟延时
await Task.Delay(50);
await Task.Delay(10);

// 模拟粘包发送后续数据
await stream.WriteAsync(new byte[] { 0x3, 0x4, 0x5, 0x6, 0x7 }, CancellationToken.None);
await stream.WriteAsync(new byte[] { 0x3, 0x4, 0x5, 0x6, 0x7, 0x3, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x1 }, CancellationToken.None);
}
}

Expand Down