private async Task RetryConnectionAsync() { try { cancellationTokenSource.Cancel(); } catch { } if (reconnectAttempts > _config.ReconnectAttempts && _config.ReconnectAttempts != -1) { return; } if (reconnectAttempts == _config.ReconnectAttempts) { _log?.Invoke(VictoriaExtensions.LogMessage(LogSeverity.Warning, $"Max number of reconnect attempts reached.")); } if (isUseable) { return; } reconnectAttempts++; interval += _config.ReconnectInterval; _log?.Invoke(VictoriaExtensions.LogMessage(LogSeverity.Warning, $"Attempt #{reconnectAttempts}. Next retry in {interval.TotalSeconds} seconds.")); await Task.Delay(interval).ContinueWith(_ => ConnectAsync()).ConfigureAwait(false); }
public Task SendPayloadAsync(BasePayload payload) { if (!isUseable) { return(Task.CompletedTask); } var serialize = JsonConvert.SerializeObject(payload); _log?.Invoke(VictoriaExtensions.LogMessage(LogSeverity.Verbose, serialize)); var seg = new ArraySegment <byte>(_encoding.GetBytes(serialize)); return(clientWebSocket.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None)); }
private async Task VerifyConnectionAsync(Task task) { if (task.IsCanceled || task.IsFaulted || task.Exception != null) { isUseable = false; await RetryConnectionAsync().ConfigureAwait(false); } else { _log?.Invoke(VictoriaExtensions.LogMessage(LogSeverity.Info, "WebSocket connection established!")); isUseable = true; reconnectAttempts = 0; await ReceiveAsync(cancellationTokenSource.Token).ConfigureAwait(false); } }
public async Task ConnectAsync() { cancellationTokenSource = new CancellationTokenSource(); clientWebSocket = new ClientWebSocket(); clientWebSocket.Options.SetRequestHeader("User-Id", $"{_config.UserId}"); clientWebSocket.Options.SetRequestHeader("Num-Shards", $"{_config.Shards}"); clientWebSocket.Options.SetRequestHeader("Authorization", _config.Password); var url = new Uri($"ws://{_config.Host}:{_config.Port}"); try { _log?.Invoke(VictoriaExtensions.LogMessage(LogSeverity.Info, $"Connecting to {url}.")); await clientWebSocket.ConnectAsync(url, CancellationToken.None).ContinueWith(VerifyConnectionAsync); } catch { // Ignore all websocket exceptions. } }