Теперь TCP клиент всё время пытается переподключиться к серверу

This commit is contained in:
Пытков Роман
2025-09-20 00:25:57 +03:00
parent 956ab61660
commit 632b618722

View File

@@ -45,30 +45,17 @@ public class TcpClientWrapper : IClient
private async Task RunAsync(CancellationToken token)
{
const int maxRetries = 5;
const int retryDelayMs = 1000;
for (int attempt = 1; attempt <= maxRetries; attempt++)
while (!token.IsCancellationRequested)
{
try
{
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(_host, _port, token);
break; // Connection successful
}
catch (Exception ex) when (attempt < maxRetries)
{
Console.WriteLine($"Connection attempt {attempt} failed: {ex.Message}. Retrying in {retryDelayMs}ms...");
await Task.Delay(retryDelayMs, token);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to connect after {maxRetries} attempts: {ex.Message}");
throw;
}
}
Console.WriteLine("Connected to server.");
using (var stream = _tcpClient!.GetStream())
using (var stream = _tcpClient.GetStream())
{
long index = 0;
var sw = Stopwatch.StartNew();
@@ -149,10 +136,23 @@ public class TcpClientWrapper : IClient
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
break; // выход из внутреннего цикла для переподключения
}
}
}
System.Console.WriteLine("End ");
Console.WriteLine("Disconnected from server. Attempting to reconnect...");
}
catch (TaskCanceledException)
{
break;
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}. Retrying in {retryDelayMs}ms...");
await Task.Delay(retryDelayMs, token);
}
}
System.Console.WriteLine("Client stopped.");
}
public override string ToString()