Skip to content

Commit e79264f

Browse files
committed
test: 增加服务器断开单元测试
1 parent e3b18d2 commit e79264f

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

test/UnitTest/Services/DefaultSocketClientProviderTest.cs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
// See the LICENSE file in the project root for more information.
44
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
55

6+
using Microsoft.Extensions.Logging;
67
using System.Net;
8+
using System.Net.Sockets;
79

810
namespace UnitTest.Services;
911

@@ -26,6 +28,35 @@ public async Task DefaultSocketClient_Ok()
2628
Assert.Equal(0, len);
2729
}
2830

31+
[Fact]
32+
public async Task ReceiveAsync_Ok()
33+
{
34+
var port = 8100;
35+
// 测试接收数据时服务器断开未连接的情况
36+
StartTcpServer(port);
37+
38+
var sc = new ServiceCollection();
39+
sc.AddBootstrapBlazorTcpSocketFactory();
40+
var provider = sc.BuildServiceProvider();
41+
var factory = provider.GetRequiredService<ITcpSocketFactory>();
42+
var client = factory.GetOrCreate("provider", op =>
43+
{
44+
op.LocalEndPoint = Utility.ConvertToIpEndPoint("localhost", 0);
45+
op.IsAutoReceive = false;
46+
op.EnableLog = false;
47+
});
48+
49+
await client.ConnectAsync("127.0.0.1", port);
50+
Assert.True(client.IsConnected);
51+
52+
var buffer = await client.ReceiveAsync();
53+
Assert.Equal(2, buffer.Length);
54+
55+
await Task.Delay(50);
56+
buffer = await client.ReceiveAsync();
57+
Assert.False(client.IsConnected);
58+
}
59+
2960
[Fact]
3061
public void SocketClientOptions_Ok()
3162
{
@@ -45,4 +76,35 @@ public void SocketClientOptions_Ok()
4576
Assert.Equal(500, options.ReceiveTimeout);
4677
Assert.Equal(new IPEndPoint(IPAddress.Loopback, 0), options.LocalEndPoint);
4778
}
79+
80+
private static TcpListener StartTcpServer(int port)
81+
{
82+
var server = new TcpListener(IPAddress.Loopback, port);
83+
server.Start();
84+
Task.Run(() => AcceptClientsAsync(server));
85+
return server;
86+
}
87+
88+
private static async Task AcceptClientsAsync(TcpListener server)
89+
{
90+
while (true)
91+
{
92+
var client = await server.AcceptTcpClientAsync();
93+
_ = Task.Run(async () =>
94+
{
95+
using var stream = client.GetStream();
96+
while (true)
97+
{
98+
var buffer = new byte[1024];
99+
100+
// 模拟拆包发送第二段数据
101+
await stream.WriteAsync(new byte[] { 0x3, 0x4 }, CancellationToken.None);
102+
103+
// 等待 20ms
104+
await Task.Delay(20);
105+
client.Close();
106+
}
107+
});
108+
}
109+
}
48110
}

0 commit comments

Comments
 (0)