private async Task Reconnect(ReconnectionType type)
        {
            IsRunning = false;
            if (_disposing)
            {
                return;
            }

            _reconnecting = true;
            if (type != ReconnectionType.Error)
            {
                _disconnectedSubject.OnNext(TranslateTypeToDisconnection(type));
            }

            _cancellation.Cancel();
            _client?.Abort();
            _client?.Dispose();

            if (!IsReconnectionEnabled)
            {
                // reconnection disabled, do nothing
                IsStarted     = false;
                _reconnecting = false;
                return;
            }

            Logger.Debug(L("Reconnecting..."));
            _cancellation = new CancellationTokenSource();
            await StartClient(_url, _cancellation.Token, type).ConfigureAwait(false);

            _reconnecting = false;
        }
예제 #2
0
 private async Task ReconnectSynchronized(ReconnectionType type, bool failFast, Exception causedException)
 {
     using (await _locker.LockAsync())
     {
         await Reconnect(type, failFast, causedException);
     }
 }
 private async Task ReconnectSynchronized(ReconnectionType type)
 {
     using (await _locker.LockAsync())
     {
         await Reconnect(type);
     }
 }
        //------------------------------------------------------------------------------------------------
        // connection
        //------------------------------------------------------------------------------------------------
        public async Task Reconnect(ReconnectionType reconnectionType, CancellationToken ct)
        {
            // determine url
            string wssurl;

            switch (this.deribitconfig.Environment)
            {
            case DeribitEnvironment.Live:
                wssurl = this.websocketurl_live_v2;
                break;

            case DeribitEnvironment.Test:
                wssurl = this.websocketurl_test_v2;
                break;

            default:
                throw new Exception();
            }
            // connect
            this.ClientWebSocket = new ClientWebSocket();
            this.logger.Information($"[{{ReconnectionType}}] Connecting to {wssurl}", reconnectionType);
            await this.ClientWebSocket.ConnectAsync(new Uri(wssurl), ct);

            this.ReconnectionHappened?.Invoke(reconnectionType);
        }
        private async Task Reconnect(ReconnectionType type)
        {
            if (_disposing)
            {
                return;
            }
            Log.Debug(L("Reconnecting..."));
            _cancelation.Cancel();
            await Task.Delay(1000);

            _cancelation = new CancellationTokenSource();
            await StartClient(_url, _cancelation.Token, type);
        }
예제 #6
0
        private Task _OnConnectAsync(ReconnectionType type)
        {
            if (type == ReconnectionType.Initial)
            {
                _Logger.LogInformation($"Stream connected");
            }
            else
            {
                _Logger.LogInformation($"{type}, reconnecting");
                _Resubscribe();
            }

            return(Task.CompletedTask);
        }
예제 #7
0
        private Task OnConnect(ReconnectionType type)
        {
            if (type == ReconnectionType.Initial)
            {
                _logger.LogInformation("Websocket Client Connected!!");
            }
            else
            {
                _logger.LogInformation("Websocket Client Reconnected!!");
            }

            _client.Subscribe(_subscription);

            return(Task.CompletedTask);
        }
예제 #8
0
        private async Task Reconnect(ReconnectionType type, bool failFast, Exception causedException)
        {
            IsRunning = false;
            if (_disposing)
            {
                return;
            }

            _reconnecting = true;

            var disType = TranslateTypeToDisconnection(type);
            var disInfo = DisconnectionInfo.Create(disType, _client, causedException);

            if (type != ReconnectionType.Error)
            {
                _disconnectedSubject.OnNext(disInfo);
                if (disInfo.CancelReconnection)
                {
                    // reconnection canceled by user, do nothing
                    Logger.Info(L($"Reconnecting canceled by user, exiting."));
                }
            }

            _cancellation.Cancel();
            try
            {
                _client?.Abort();
            }
            catch (Exception e)
            {
                Logger.Error(e, L($"Exception while aborting client. " + $"Error: '{e.Message}'"));
            }
            _client?.Dispose();

            if (!IsReconnectionEnabled || disInfo.CancelReconnection)
            {
                // reconnection disabled, do nothing
                IsStarted     = false;
                _reconnecting = false;
                return;
            }

            Logger.Debug(L("Reconnecting..."));
            _cancellation = new CancellationTokenSource();
            await StartClient(_url, _cancellation.Token, type, failFast).ConfigureAwait(false);

            _reconnecting = false;
        }
예제 #9
0
        private async Task Reconnect(ReconnectionType type)
        {
            IsRunning = false;
            if (_disposing)
            {
                return;
            }
            if (type != ReconnectionType.Error)
            {
                //_disconnectedSubject.OnNext(TranslateTypeToDisconnection(type));
            }

            _cancelation.Cancel();
            await Task.Delay(1000).ConfigureAwait(false);

            _cancelation = new CancellationTokenSource();
            await StartClient(new Uri(_url), _cancelation.Token, type).ConfigureAwait(false);
        }
        private async Task StartClient(Uri uri, CancellationToken token, ReconnectionType type)
        {
            DeactiveLastChance();
            _client = _clientFactory();

            try
            {
                await _client.ConnectAsync(uri, token);

#pragma warning disable 4014
                Listen(_client, token);
#pragma warning restore 4014
                ActivateLastChance();
                _reconnectionSubject.OnNext(type);
            }
            catch (Exception e)
            {
                Log.Error(e, L("Exception while connecting. " +
                               $"Waiting {ErrorReconnectTimeoutMs/1000} sec before next reconnection try."));
                await Task.Delay(ErrorReconnectTimeoutMs, token);
                await Reconnect(ReconnectionType.Error);
            }
        }
 /// <inheritdoc />
 public ReconnectionInfo(ReconnectionType type)
 {
     Type = type;
 }
 /// <summary>
 /// Simple factory method
 /// </summary>
 public static ReconnectionInfo Create(ReconnectionType type)
 {
     return(new ReconnectionInfo(type));
 }
        //------------------------------------------------------------------------------------------------
        // reconnection
        //------------------------------------------------------------------------------------------------

        private void Jsonrpc_ReconnectionHappened(ReconnectionType obj)
        {
            this.jsonrpc.RpcProxy.subscription += this.handle_notification;
        }
예제 #14
0
        private async Task StartClient(Uri uri, CancellationToken token, ReconnectionType type)
        {
            // also check if connection was lost, that's probably why we get called multiple times.
            if (_clientWebSocket == null || _clientWebSocket.State != WebSocketState.Open)
            {
                // create a new web-socket so the next connect call works.
                _clientWebSocket?.Dispose();
                //var options = new ClientWebSocketOptions();
                _clientWebSocket = new ClientWebSocket();
                _clientWebSocket.Options.KeepAliveInterval = new TimeSpan(0, 0, 15, 0);

                if (!string.IsNullOrEmpty(_token))
                {
                    _clientWebSocket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
                }
            }
            // don't do anything, we are already connected.
            else
            {
                return;
            }
            try
            {
                //await _clientWebSocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);
                await _clientWebSocket.ConnectAsync(uri, token).ConfigureAwait(false);

                OnConnect?.Invoke(this, EventArgs.Empty);
                IsRunning = true;
                await Receive(_clientWebSocket, token, async (receivedMessage) =>
                {
                    JObject jObject = null;
                    InvocationDescriptor invocationDescriptor = null;
                    try
                    {
                        jObject = Newtonsoft.Json.JsonConvert.DeserializeObject <JObject>(receivedMessage);
                        //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(serializedMessage);
                        invocationDescriptor = jObject.ToObject <InvocationDescriptor>();
                        //if (invocationDescriptor == null) return;
                    }
                    catch (Exception ex)
                    {
                        // ignore invalid data sent to the server.
                    }
                    if (jObject == null)
                    {
                        try
                        {
                            var obj = MethodInvocationStrategy.OnTextReceivedAsync("", receivedMessage);
                        }
                        catch (Exception ex)
                        {
                        }
                        return;
                    }
                    if (invocationDescriptor != null && invocationDescriptor.Params != null)
                    {
                        if (invocationDescriptor.Id == 0)
                        {
                            // invoke the method only.
                            try
                            {
                                await MethodInvocationStrategy.OnInvokeMethodReceivedAsync("", invocationDescriptor);
                            }
                            catch (Exception)
                            {
                                // we consume all exceptions.
                                return;
                            }
                        }
                        else
                        {
                            // invoke the method and get the result.
                            InvocationResult invokeResult;
                            try
                            {
                                // create an invocation result with the results.
                                invokeResult = new InvocationResult()
                                {
                                    Id        = invocationDescriptor.Id,
                                    Result    = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync("", invocationDescriptor),
                                    Exception = null
                                };
                            }
                            // send the exception as the invocation result if there was one.
                            catch (Exception ex)
                            {
                                invokeResult = new InvocationResult()
                                {
                                    Id        = invocationDescriptor.Id,
                                    Result    = null,
                                    Exception = new RemoteException(ex)
                                };
                            }

                            // send a message to the server containing the result.
                            var message = new Message()
                            {
                                MessageType = MessageType.MethodReturnValue,
                                Data        = JsonConvert.SerializeObject(invokeResult)
                            };
                            //var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, _jsonSerializerSettings));
                            //var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message.Data, _jsonSerializerSettings));
                            //await _clientWebSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false);
                            await Send(message.Data);
                        }
                    }
                    else
                    {
                        try
                        {
                            var invocationResult = jObject.ToObject <InvocationResult>();
                            if ((invocationResult != null) && (invocationResult.Exception != null || invocationResult.Result != null))
                            {
                                // find the completion source in the waiting list.
                                if (_waitingRemoteInvocations.ContainsKey(invocationResult.Id))
                                {
                                    // set the result of the completion source so the invoke method continues executing.
                                    _waitingRemoteInvocations[invocationResult.Id].SetResult(invocationResult);
                                    // remove the completion source from the waiting list.
                                    _waitingRemoteInvocations.Remove(invocationResult.Id);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            var str = e.Message;
                        }
                    }
                });

                ActivateLastChance();
            }
            catch (Exception e)
            {
                Console.WriteLine($"{DateTime.Now} _clientWebSocket.ConnectAsync Exception: {e.Message}");
                IsRunning = false;
                await Task.Delay(ErrorReconnectTimeoutMs, _cancelation.Token).ConfigureAwait(false);
                await Reconnect(ReconnectionType.Error).ConfigureAwait(false);
            }
        }
예제 #15
0
        //------------------------------------------------------------------------------------------------
        // reconnection
        //------------------------------------------------------------------------------------------------

        private void Jsonrpc_ReconnectionHappened(ReconnectionType obj)
        {
            this.jsonrpc.RpcProxy.heartbeat += this.handle_heartbeat;
        }
예제 #16
0
 public void UpdateDiscordWebSocketState(ReconnectionType type)
 {
     IsDiscordBotConnected = true;
     retryTimer.Stop();
     RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(DiscordSocketStateMessage)));
 }
예제 #17
0
 protected void handleReconnect(ReconnectionType type)
 {
     sendLogIn();
 }