Skip to content

Commit 8b8a0b7

Browse files
committed
feat: 增加连接超时功能
1 parent 8e3d048 commit 8b8a0b7

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,37 @@ public async ValueTask<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken
5353

5454
// 创建新的 TcpClient 实例
5555
_client ??= new TcpClient(LocalEndPoint);
56-
await _client.ConnectAsync(endPoint, token);
5756

58-
// 开始接收数据
59-
_ = Task.Run(ReceiveAsync, token);
57+
var connectionToken = token;
58+
if (ConnectTimeout > 0)
59+
{
60+
// 设置连接超时时间
61+
var connectTokenSource = new CancellationTokenSource(ConnectTimeout);
62+
connectionToken = CancellationTokenSource.CreateLinkedTokenSource(token, connectTokenSource.Token).Token;
63+
}
64+
await _client.ConnectAsync(endPoint, connectionToken);
6065

66+
// 设置本地以及远端端点信息
6167
LocalEndPoint = (IPEndPoint)_client.Client.LocalEndPoint!;
6268
_remoteEndPoint = endPoint;
69+
70+
if (IsAutoReceive)
71+
{
72+
// 开始接收数据
73+
_ = Task.Run(ReceiveAsync, token);
74+
}
6375
ret = true;
6476
}
6577
catch (OperationCanceledException ex)
6678
{
67-
Logger.LogWarning(ex, "TCP Socket connect operation was canceled from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, endPoint);
79+
if (token.IsCancellationRequested)
80+
{
81+
Logger.LogWarning(ex, "TCP Socket connect operation was canceled from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, endPoint);
82+
}
83+
else
84+
{
85+
Logger.LogWarning(ex, "TCP Socket connect operation timed out from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, endPoint);
86+
}
6887
}
6988
catch (Exception ex)
7089
{

0 commit comments

Comments
 (0)