Added auto reconnect on first try

This commit is contained in:
EonaCat 2025-08-22 19:01:51 +02:00
parent 00aab13685
commit 8c6eccb53f
2 changed files with 33 additions and 8 deletions

View File

@ -15,6 +15,12 @@ namespace EonaCat.Connections.Client.Example
while (true) while (true)
{ {
if (!_client.IsConnected)
{
await Task.Delay(1000).ConfigureAwait(false);
continue;
}
Console.Write("Enter message to send (or 'exit' to quit): "); Console.Write("Enter message to send (or 'exit' to quit): ");
var message = Console.ReadLine(); var message = Console.ReadLine();
@ -46,10 +52,19 @@ namespace EonaCat.Connections.Client.Example
_client = new NetworkClient(config); _client = new NetworkClient(config);
_client.OnGeneralError += (sender, e) =>
Console.WriteLine($"Error: {e.Message}");
// Subscribe to events // Subscribe to events
_client.OnConnected += (sender, e) => _client.OnConnected += async (sender, e) =>
{ {
Console.WriteLine($"Connected to server at {e.RemoteEndPoint}"); Console.WriteLine($"Connected to server at {e.RemoteEndPoint}");
// Send nickname
await _client.SendNicknameAsync("TestUser");
// Send a message
await _client.SendAsync("Hello server!");
}; };
_client.OnDataReceived += (sender, e) => _client.OnDataReceived += (sender, e) =>
@ -60,13 +75,8 @@ namespace EonaCat.Connections.Client.Example
Console.WriteLine("Disconnected from server"); Console.WriteLine("Disconnected from server");
}; };
Console.WriteLine("Connecting to server...");
await _client.ConnectAsync(); await _client.ConnectAsync();
// Send nickname
await _client.SendNicknameAsync("TestUser");
// Send a message
await _client.SendAsync("Hello server!");
} }
} }
} }

View File

@ -24,6 +24,8 @@ namespace EonaCat.Connections
private CancellationTokenSource _cancellation; private CancellationTokenSource _cancellation;
private bool _isConnected; private bool _isConnected;
public bool IsConnected => _isConnected;
public event EventHandler<ConnectionEventArgs> OnConnected; public event EventHandler<ConnectionEventArgs> OnConnected;
public event EventHandler<DataReceivedEventArgs> OnDataReceived; public event EventHandler<DataReceivedEventArgs> OnDataReceived;
public event EventHandler<ConnectionEventArgs> OnDisconnected; public event EventHandler<ConnectionEventArgs> OnDisconnected;
@ -106,12 +108,17 @@ namespace EonaCat.Connections
} }
catch (Exception ex) catch (Exception ex)
{ {
_isConnected = false;
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect" }); OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect" });
await Task.Run(() => AutoReconnectAsync());
} }
} }
public string IpAddress => _config != null ? _config.Host : string.Empty; public string IpAddress => _config != null ? _config.Host : string.Empty;
public int Port => _config != null ? _config.Port : 0; public int Port => _config != null ? _config.Port : 0;
public bool IsAutoReconnecting { get; private set; }
private async Task ConnectUdp() private async Task ConnectUdp()
{ {
await Task.Run(() => await Task.Run(() =>
@ -129,6 +136,7 @@ namespace EonaCat.Connections
} }
catch (Exception ex) catch (Exception ex)
{ {
_isConnected = false;
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect UDP" }); OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect UDP" });
} }
}); });
@ -186,8 +194,8 @@ namespace EonaCat.Connections
} }
catch (Exception ex) catch (Exception ex)
{ {
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error receiving data" });
_isConnected = false; _isConnected = false;
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error receiving data" });
_ = Task.Run(() => AutoReconnectAsync()); _ = Task.Run(() => AutoReconnectAsync());
break; break;
@ -377,6 +385,11 @@ namespace EonaCat.Connections
return; return;
} }
if (IsAutoReconnecting)
{
return;
}
int attempt = 0; int attempt = 0;
while (!_isConnected && (_config.MaxReconnectAttempts == 0 || attempt < _config.MaxReconnectAttempts)) while (!_isConnected && (_config.MaxReconnectAttempts == 0 || attempt < _config.MaxReconnectAttempts))
@ -385,10 +398,12 @@ namespace EonaCat.Connections
try try
{ {
OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Attempting to reconnect (Attempt {attempt})" }); OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Attempting to reconnect (Attempt {attempt})" });
IsAutoReconnecting = true;
await ConnectAsync(); await ConnectAsync();
if (_isConnected) if (_isConnected)
{ {
IsAutoReconnecting = false;
OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Reconnected successfully after {attempt} attempt(s)" }); OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Reconnected successfully after {attempt} attempt(s)" });
break; break;
} }