Skip to content

Commit

Permalink
Add timeout before reconnecting when the listened stream is lost (#127)
Browse files Browse the repository at this point in the history
Add timeout before reconnecting if the connection is lost with a transient error.

Co-authored-by: Denis Sidenko <[email protected]>
  • Loading branch information
densidenko and Denis Sidenko authored Sep 1, 2023
1 parent 638cf7f commit 1592f69
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/Websocket.Client/IWebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ public interface IWebsocketClient : IDisposable
/// Default: 1 minute.
/// </summary>
TimeSpan? ErrorReconnectTimeout { get; set; }

/// <summary>
/// Time range in ms, how long to wait before reconnecting if connection is lost with a transient error.
/// Set null to disable this feature.
/// Default: 0 ms (immediately)
/// </summary>
TimeSpan? LostReconnectTimeout { get; set; }

/// <summary>
/// Get or set the name of the current websocket client instance.
Expand Down
16 changes: 15 additions & 1 deletion src/Websocket.Client/WebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,13 @@ public Uri Url
/// </summary>
public TimeSpan? ErrorReconnectTimeout { get; set; } = TimeSpan.FromMinutes(1);

/// <summary>
/// Time range in ms, how long to wait before reconnecting if connection is lost with a transient error.
/// Set null to disable this feature.
/// Default: 0 ms (immediately)
/// </summary>
public TimeSpan? LostReconnectTimeout { get; set; }

/// <summary>
/// Enable or disable reconnection functionality (enabled by default)
/// </summary>
Expand Down Expand Up @@ -560,12 +567,19 @@ await StopInternal(client, WebSocketCloseStatus.NormalClosure, "Closing",
causedException = e;
}


if (ShouldIgnoreReconnection(client) || !IsStarted)
{
// reconnection already in progress or client stopped/disposed, do nothing
return;
}

if (LostReconnectTimeout.HasValue)
{
var timeout = LostReconnectTimeout.Value;
Logger.Warn(L("Listening websocket stream is lost. " +
$"Waiting {timeout.TotalSeconds} sec before next reconnection try."));
await Task.Delay(timeout, token).ConfigureAwait(false);
}

// listening thread is lost, we have to reconnect
_ = ReconnectSynchronized(ReconnectionType.Lost, false, causedException);
Expand Down

0 comments on commit 1592f69

Please sign in to comment.