Пример #1
0
        public async Task <bool> ConnectAsync()
        {
            if (_client == null)
            {
                _client = new WebsocketClient(new Uri(_clientAddress))
                {
                    ReconnectTimeout = null // this is to prevent the client from auto disconnecting if we are not getting a response within X time
                };
                _client.ReconnectionHappened.Subscribe(async r => await OnReconnect(r));
                _client.MessageReceived.Subscribe(async m => await OnMessage(m));
                _client.DisconnectionHappened.Subscribe(async d => await Disconnected(d));
            }

            if (IsConnected)
            {
                return(true); // we are already connected, no need to connect again
            }
            try
            {
                await _client.StartOrFail();
                await Connected(); // trigger event and logger

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #2
0
        public async Task <IWebsocketClient> InitAsync()
        {
            if (_logger.IsInfo)
            {
                _logger.Info($"Starting ETH stats [{_urlFromConfig}]...");
            }
            string websocketUrl = BuildUrl();
            Uri    url          = new Uri(websocketUrl);

            _client = new WebsocketClient(url)
            {
                ErrorReconnectTimeout = TimeSpan.FromMilliseconds(_reconnectionInterval),
                ReconnectTimeout      = null
            };

            _client.MessageReceived.Subscribe(async message =>
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Received ETH stats message '{message}'");
                }
                if (string.IsNullOrWhiteSpace(message.Text))
                {
                    return;
                }

                if (message.Text.Contains(ServerPingMessage))
                {
                    await HandlePingAsync(message.Text);
                }
            });

            try
            {
                await _client.StartOrFail();
            }
            catch (Exception e)
            {
                if (!_client.Url.AbsoluteUri.EndsWith("/api"))
                {
                    _client.Url = new Uri(websocketUrl + "/api");
                }

                await _client.StartOrFail();
            }

            if (_logger.IsDebug)
            {
                _logger.Debug($"Started ETH stats.");
            }

            return(_client);
        }
Пример #3
0
        private async Task StartSocketAsync()
        {
            var disconnects = new List <DisconnectEvent>();
            var messages    = new List <ResponseMessage>();

            //start temporary collecting messages and disconnects to local collection
            using IDisposable disconnectSubscription = _socket.DisconnectionHappened
                                                       .Select(info => new DisconnectEvent(info.CloseStatus, info.CloseStatusDescription, info.Exception)).Subscribe(disconnects.Add);
            using IDisposable messageSubscription = _socket.MessageReceived.Subscribe(messages.Add);

            //wait until start finishes
            await _socket.StartOrFail();

            //start real subscriptions and prepend any temporary collected data to them
            _disconnectSubscription = _socket.DisconnectionHappened
                                      .Select(info => new DisconnectEvent(info.CloseStatus, info.CloseStatusDescription, info.Exception))
                                      .StartWith(disconnects)
                                      .Subscribe(Events.DisconnectSubject);
            _messageSubscription = _socket.MessageReceived.StartWith(messages).Subscribe(OnMessage);
        }
Пример #4
0
        public async Task ConnectAsync(CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(_token))
            {
                throw new InvalidOperationException("Токен не установлен");
            }

            if (_ws.NativeClient?.State == WebSocketState.Open && _authorized)
            {
                return;
            }

            await _ws.StartOrFail();

            var connectCommand = new Command
            {
                Id     = InterlockedEx.Increment(ref _nextOperationId),
                Method = MethodType.Connect,
                Params = new ConnectRequest
                {
                    Token = _token
                }.ToByteString()
            };

            // TODO: retry with exponential backoff, reinit connection on connection lost
            var response = await HandleCommand(connectCommand, cancellationToken);

            var connectResult = ConnectResult.Parser.ParseFrom(response);

            _authorized = true;
            //_clientId = authResult.Client;

            _connectedEventSource.OnNext(new ConnectedEvent
            {
                Client  = Guid.Parse(connectResult.Client),
                Expires = connectResult.Expires,
                Ttl     = connectResult.Ttl,
                Version = connectResult.Version
            });
        }