Skip to content

Commit a9bfbfb

Browse files
committed
refactor: 合并重连方法提高可读性
1 parent 5ddbe3c commit a9bfbfb

File tree

1 file changed

+25
-28
lines changed

1 file changed

+25
-28
lines changed

src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -100,42 +100,42 @@ public async ValueTask<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken
100100
try
101101
{
102102
ret = await ConnectCoreAsync(SocketClientProvider, endPoint, token);
103-
if (ret == false)
104-
{
105-
Reconnect();
106-
}
107103
}
108104
catch (OperationCanceledException ex)
109105
{
110106
if (token.IsCancellationRequested)
111107
{
112108
Log(LogLevel.Warning, ex, $"TCP Socket connect operation was canceled from {LocalEndPoint} to {endPoint}");
109+
reconnect = false;
113110
}
114111
else
115112
{
116113
Log(LogLevel.Warning, ex, $"TCP Socket connect operation timed out from {LocalEndPoint} to {endPoint}");
117-
Reconnect();
118114
}
119115
}
120116
catch (Exception ex)
121117
{
122118
Log(LogLevel.Error, ex, $"TCP Socket connection failed from {LocalEndPoint} to {endPoint}");
119+
}
120+
121+
if (!ret && reconnect)
122+
{
123123
Reconnect();
124124
}
125125
return ret;
126126
}
127127

128128
private void Reconnect()
129129
{
130-
if (options.IsAutoReconnect)
130+
if (options.IsAutoReconnect && _remoteEndPoint != null)
131131
{
132132
Task.Run(async () =>
133133
{
134134
try
135135
{
136136
_autoConnectTokenSource ??= new();
137137
await Task.Delay(options.ReconnectInterval, _autoConnectTokenSource.Token).ConfigureAwait(false);
138-
HandleDisconnection();
138+
await ConnectAsync(_remoteEndPoint, _autoConnectTokenSource.Token).ConfigureAwait(false);
139139
}
140140
catch { }
141141
}, CancellationToken.None).ConfigureAwait(false);
@@ -174,15 +174,6 @@ private async ValueTask<bool> ConnectCoreAsync(ISocketClientProvider provider, I
174174
return ret;
175175
}
176176

177-
private void HandleDisconnection()
178-
{
179-
if (options.IsAutoReconnect && _remoteEndPoint != null)
180-
{
181-
_autoConnectTokenSource ??= new();
182-
_ = Task.Run(() => ConnectAsync(_remoteEndPoint, _autoConnectTokenSource.Token)).ConfigureAwait(false);
183-
}
184-
}
185-
186177
/// <summary>
187178
/// <inheritdoc/>
188179
/// </summary>
@@ -197,6 +188,7 @@ public virtual async ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, Cancel
197188
}
198189

199190
var ret = false;
191+
var reconnect = true;
200192
try
201193
{
202194
var sendToken = token;
@@ -207,15 +199,12 @@ public virtual async ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, Cancel
207199
sendToken = CancellationTokenSource.CreateLinkedTokenSource(token, sendTokenSource.Token).Token;
208200
}
209201
ret = await SocketClientProvider.SendAsync(data, sendToken);
210-
if (ret == false)
211-
{
212-
HandleDisconnection();
213-
}
214202
}
215203
catch (OperationCanceledException ex)
216204
{
217205
if (token.IsCancellationRequested)
218206
{
207+
reconnect = false;
219208
Log(LogLevel.Warning, ex, $"TCP Socket send operation was canceled from {_localEndPoint} to {_remoteEndPoint}");
220209
}
221210
else
@@ -226,14 +215,18 @@ public virtual async ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, Cancel
226215
catch (Exception ex)
227216
{
228217
Log(LogLevel.Error, ex, $"TCP Socket send failed from {_localEndPoint} to {_remoteEndPoint}");
229-
230-
HandleDisconnection();
231218
}
232219

233220
if (options.EnableLog)
234221
{
235222
Log(LogLevel.Information, null, $"Sending data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {data.Length} Data Content: {BitConverter.ToString(data.ToArray())} Result: {ret}");
236223
}
224+
225+
if (!ret && reconnect)
226+
{
227+
// 如果发送失败并且需要重连则尝试重连
228+
Reconnect();
229+
}
237230
return ret;
238231
}
239232

@@ -259,7 +252,7 @@ public virtual async ValueTask<Memory<byte>> ReceiveAsync(CancellationToken toke
259252
var len = await ReceiveCoreAsync(SocketClientProvider, buffer, token);
260253
if (len == 0)
261254
{
262-
HandleDisconnection();
255+
Reconnect();
263256
}
264257
return buffer[..len];
265258
}
@@ -285,11 +278,12 @@ private async ValueTask AutoReceiveAsync()
285278
}
286279
}
287280

288-
HandleDisconnection();
281+
Reconnect();
289282
}
290283

291284
private async ValueTask<int> ReceiveCoreAsync(ISocketClientProvider client, Memory<byte> buffer, CancellationToken token)
292285
{
286+
var reconnect = true;
293287
var len = 0;
294288
try
295289
{
@@ -307,8 +301,6 @@ private async ValueTask<int> ReceiveCoreAsync(ISocketClientProvider client, Memo
307301
// 远端主机关闭链路
308302
Log(LogLevel.Information, null, $"TCP Socket {_localEndPoint} received 0 data closed by {_remoteEndPoint}");
309303
buffer = Memory<byte>.Empty;
310-
311-
HandleDisconnection();
312304
}
313305
else
314306
{
@@ -326,6 +318,7 @@ private async ValueTask<int> ReceiveCoreAsync(ISocketClientProvider client, Memo
326318
if (token.IsCancellationRequested)
327319
{
328320
Log(LogLevel.Warning, ex, $"TCP Socket receive operation canceled from {_localEndPoint} to {_remoteEndPoint}");
321+
reconnect = false;
329322
}
330323
else
331324
{
@@ -335,14 +328,18 @@ private async ValueTask<int> ReceiveCoreAsync(ISocketClientProvider client, Memo
335328
catch (Exception ex)
336329
{
337330
Log(LogLevel.Error, ex, $"TCP Socket receive failed from {_localEndPoint} to {_remoteEndPoint}");
338-
339-
HandleDisconnection();
340331
}
341332

342333
if (options.EnableLog)
343334
{
344335
Log(LogLevel.Information, null, $"Receiving data from {_localEndPoint} to {_remoteEndPoint}, Data Length: {len} Data Content: {BitConverter.ToString(buffer.ToArray())}");
345336
}
337+
338+
if (len == 0 && reconnect)
339+
{
340+
// 如果接收数据长度为 0 并且需要重连则尝试重连
341+
Reconnect();
342+
}
346343
return len;
347344
}
348345

0 commit comments

Comments
 (0)