Example #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);
            }
        }
        static async Task Main(string[] args)
        {
            Console.WriteLine("Push any key to start");

            Console.ReadLine();

            _client = new WebsocketClient(new ParamsWSClient
            {
                IsWebsocketSecured = false,
                Port = 65214,
                Uri  = "localhost",
                RequestedSubProtocols = new string[] { "testProtocol", "test2", "test3" },
                RequestHeaders        = new Dictionary <string, string> {
                    { HttpKnownHeaderNames.From, "Robbie" }
                },
                KeepAliveInterval = TimeSpan.FromSeconds(5)
            }, token: "Test");
            _client.ConnectionEvent += OnConnectionEvent;
            _client.MessageEvent    += OnMessageEvent;
            _client.ErrorEvent      += OnErrorEvent;
            await _client.ConnectAsync();

            while (true)
            {
                await _client.SendToServerAsync(Console.ReadLine());
            }
        }
Example #3
0
        public async Task OpenAsync(Uri uri, SocketIoOpenOptions options = null)
        {
            ThrowIfStarted();

            try
            {
                Logger.LogInformation($"Opening socket connection to: {uri}");

                State      = ReadyState.Opening;
                _namespace = uri.LocalPath;
                _query     = string.IsNullOrEmpty(uri.Query) ? null : uri.Query.TrimStart('?');
                var socketIoUri = uri.ToSocketIoWebSocketUri(path: options?.Path);
                _socket = new WebsocketClient(socketIoUri)
                {
                    MessageEncoding = Encoding, IsReconnectionEnabled = false
                };

                Events.HandshakeSubject.Subscribe(OnHandshake);
                Events.OnPong.Subscribe(OnPong);
                Events.OnOpen.Subscribe(OnOpen);

                await StartSocketAsync();

                State = ReadyState.Open;
                Logger.LogInformation("Socket connection successfully established.");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error while starting socket.");
                State = ReadyState.Closed;
                throw;
            }
        }
Example #4
0
        public Client()
        {
            InitLogging();
            WaitUntilServerStarts();
            var factory = new Func <ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(5000),
                        // Proxy = ...
                        // ClientCertificates = ...
                    }
                };
                //client.Options.SetRequestHeader("Origin", "xxx");
                return(client);
            });

            webSocketClient = new WebsocketClient(serverUrl, factory)
            {
                Name = "First Client"
            };
            webSocketClient.DisconnectionHappened.Subscribe(info =>
                                                            Log.Warning($"Disconnection happened, type: {info.Type}"));

            Log.Information("Starting...");
            webSocketClient.Start().Wait();
            Log.Information("Started.");
            //var res = SendAsync("ping").Result;

            //Log.Information($"Message received: {res}");

            //ExitEvent.WaitOne();
        }
 private Task SendBlockAsync(IWebsocketClient client, Core.Block block)
 => _sender.SendAsync(client, new BlockMessage(new Block(block.Number, block.Hash?.ToString(),
                                                         block.ParentHash?.ToString(),
                                                         (long)block.Timestamp, block.Author?.ToString(), block.GasUsed, block.GasLimit,
                                                         block.Difficulty.ToString(), block.TotalDifficulty?.ToString(),
                                                         block.Transactions?.Select(t => new Transaction(t.Hash?.ToString())) ?? Enumerable.Empty <Transaction>(),
                                                         block.TransactionsRoot.ToString(), block.StateRoot.ToString(),
                                                         block.Ommers?.Select(o => new Uncle()) ?? Enumerable.Empty <Uncle>())));
Example #6
0
        private static async Task StartSendingPing(IWebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(1000);

                await client.Send("ping");
            }
        }
Example #7
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);
        }
        public Task SendAsync <T>(IWebsocketClient client, T message, string type = null) where T : IMessage
        {
            var(emitMessage, messageType) = CreateMessage(message, type);
            var payload = JsonConvert.SerializeObject(emitMessage, SerializerSettings);

            if (_logger.IsTrace)
            {
                _logger.Trace($"Sending ETH stats message '{messageType}': {payload}");
            }

            return(client.Send(payload));
        }
        public WebSocketClient(string url)
        {
            var factory = new Func <ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(5)
                    }
                };
                return(client);
            });

            _ws = new WebsocketClient(new Uri(url), factory)
            {
                Name                  = url,
                ReconnectTimeout      = TimeSpan.FromSeconds(RECONNECT_TIMEOUT_SECONDS),
                ErrorReconnectTimeout = TimeSpan.FromSeconds(ERROR_RECONNECT_TIMEOUT_SECONDS)
            };

            _ws.ReconnectionHappened.Subscribe(type =>
            {
                Log.Debug($"WebSocket {_ws.Url} opened.");
                Connected?.Invoke(this, null);
            }
                                               );

            _ws.DisconnectionHappened.Subscribe(info =>
            {
                Log.Debug($"WebSocket {_ws.Url } closed.");
                Disconnected?.Invoke(this, null);
            }
                                                );

            _ws.MessageReceived.Subscribe(msg =>
            {
                if (msg.MessageType == WebSocketMessageType.Binary)
                {
                    OnBinaryMessage(msg.Binary);
                }
                else if (msg.MessageType == WebSocketMessageType.Text)
                {
                    OnTextMessage(msg.Text);
                }
                else
                {
                    throw new NotSupportedException("Unsupported web socket message type");
                }

                OnMessage?.Invoke(this, msg);
            });
        }
Example #10
0
 public WSClientAC(string accessToken, string uri = "connect.allie.chat", int port = 7615, bool isWSS = true)
 {
     _websocketClient = new WebsocketClient(new ParamsWSClient
     {
         IsWebsocketSecured = isWSS,
         Port = port,
         Uri  = uri
     }, accessToken);
     _websocketClient.ConnectionEvent += OnConnectionEvent;
     _websocketClient.MessageEvent    += OnMessageEvent;
     _websocketClient.ErrorEvent      += OnErrorEvent;
 }
Example #11
0
        private static async Task SwitchUrl(IWebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(10000);

                var production = new Uri("wss://localhost:8181");
                var testnet    = new Uri("wss://localhost:8182");
                var selected   = client.Url == production ? testnet : production;
                client.Url = selected;
                await client.Reconnect();
            }
        }
Example #12
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    _client?.Dispose();
                    _client = null;
                }

                isDisposed = true;
            }
        }
Example #13
0
        private static async Task SwitchUrl(IWebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(10000);

                var production = new Uri("wss://www.bitmex.com/realtime");
                var testnet    = new Uri("wss://testnet.bitmex.com/realtime");

                var selected = client.Url == production ? testnet : production;
                client.Url = selected;
                await client.Reconnect();
            }
        }
Example #14
0
        private static async Task StartSendingPing(IWebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(1000);

                if (!client.IsRunning)
                {
                    continue;
                }

                await client.Send("ping");
            }
        }
Example #15
0
        private static async Task StartSendingPing(IWebsocketClient client)
        {
            while (true)
            {
                await Task.Delay(5000);

                if (!client.IsRunning)
                {
                    continue;
                }

                client.Send($"ping{DateTime.Now.Second}");
                Console.WriteLine($"ping{DateTime.Now.Second}");
            }
        }
        private async Task SwitchUrl(IWebsocketClient client, CancellationToken cancellation)
        {
            while (true)
            {
                await Task.Delay(200000);

                if (cancellation.IsCancellationRequested)
                {
                    return;
                }

                client.Url = urlAuth;
                await client.Reconnect();
            }
        }
Example #17
0
        public async Task InitAsync()
        {
            var timer = new System.Timers.Timer {
                Interval = SendStatsInterval
            };

            timer.Elapsed           += TimerOnElapsed;
            _blockTree.NewHeadBlock += BlockTreeOnNewHeadBlock;
            var exitEvent = new ManualResetEvent(false);

            using (_websocketClient = await _ethStatsClient.InitAsync())
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("Initial connection, sending 'hello' message...");
                }
                await SendHelloAsync();

                _connected = true;
                _websocketClient.ReconnectionHappened.Subscribe(async reason =>
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("ETH Stats reconnected, sending 'hello' message...");
                    }
                    await SendHelloAsync();
                    _connected = true;
                });
                _websocketClient.DisconnectionHappened.Subscribe(reason =>
                {
                    _connected = false;
                    if (_logger.IsWarn)
                    {
                        _logger.Warn($"ETH Stats disconnected, reason: {reason}");
                    }
                });

                timer.Start();
                exitEvent.WaitOne();
            }

            _connected = false;
            timer.Stop();
            timer.Dispose();
            _blockTree.NewHeadBlock -= BlockTreeOnNewHeadBlock;
            timer.Elapsed           -= TimerOnElapsed;
        }
Example #18
0
 protected override void MessageReceived(MessageReceived message, IWebsocketClient client)
 {
     try
     {
         if (message != null)
         {
             var result = HandlerMessages?.Invoke(message);
             if (result.HasValue && result.Value)
             {
                 Task.Run(() =>
                 {
                     try
                     {
                         using (var c = new ConfirmMessage(this.keyAccess, this.privateKey))
                         {
                             c.Ok(message.data.Info.Id, message.data.Info.RemoteJid);
                         }
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine(ex);
                     }
                 });
                 Task.Run(() =>
                 {
                     try
                     {
                         client.Send(JsonConvert.SerializeObject(new
                         {
                             Token = keyAccess,
                             message.data.Info.Id,
                             message.data.Info.RemoteJid
                         }));
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine(ex);
                     }
                 });
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
        public async Task ConnectAsync()
        {
            _client = new WebsocketClient(GetEndpoint(), wsFactory)
            {
                ReconnectTimeout      = TimeSpan.FromSeconds(35),
                ErrorReconnectTimeout = TimeSpan.FromSeconds(30)
            };

            _client.DisconnectionHappened.Subscribe(info =>
            {
                _logger.LogWarning(75421, $"Stream disconnected: {info.Type}: {info.Exception}");

                if (_onDisconnected != null)
                {
                    Task.Run(() => _onDisconnected(info));
                }
            });

            _client.ReconnectionHappened.Subscribe(info =>
            {
                if (info.Type == ReconnectionType.Initial)
                {
                    _logger.LogInformation("Starting initial census stream connect");
                }
                else
                {
                    _logger.LogInformation($"Stream reconnection occured: {info.Type}");
                }

                if (_onConnect != null)
                {
                    Task.Run(() => _onConnect(info.Type));
                }
            });

            _client.MessageReceived.Subscribe(msg =>
            {
                if (_onMessage != null)
                {
                    Task.Run(() => _onMessage(msg.Text));
                }
            });

            await _client.Start();
        }
        private async Task StartSendingPing(IWebsocketClient client, CancellationToken cancellation)
        {
            while (true)
            {
                await Task.Delay(10000);

                if (cancellation.IsCancellationRequested)
                {
                    return;
                }

                if (!client.IsRunning)
                {
                    continue;
                }

                client.Send("ping");
            }
        }
        public async Task InitAsync()
        {
            _timer = new Timer {
                Interval = SendStatsInterval
            };
            _timer.Elapsed          += TimerOnElapsed;
            _blockTree.NewHeadBlock += BlockTreeOnNewHeadBlock;
            _websocketClient         = await _ethStatsClient.InitAsync();

            if (_logger.IsInfo)
            {
                _logger.Info("Initial connection, sending 'hello' message...");
            }
            await SendHelloAsync();

            _connected = true;

            Run(_timer);
        }
        public async Task ConnectAsync(CensusStreamSubscription subscription)
        {
            _client = new WebsocketClient(GetEndpoint(), wsFactory)
            {
                ReconnectTimeout      = TimeSpan.FromSeconds(35),
                ErrorReconnectTimeout = TimeSpan.FromSeconds(30)
            };

            _client.DisconnectionHappened.Subscribe(info =>
            {
                _logger.LogWarning(75421, $"Stream disconnected: {info.Type}: {info.Exception}");

                if (_onDisconnected != null)
                {
                    Task.Run(() => _onDisconnected(info));
                }
            });

            _client.ReconnectionHappened.Subscribe(info =>
            {
                _logger.LogInformation($"Stream reconnection occured: {info.Type}");

                if (subscription.EventNames.Any())
                {
                    var sMessage = JsonConvert.SerializeObject(subscription, sendMessageSettings);

                    _client.Send(sMessage);

                    _logger.LogInformation($"Subscribed to census with: {sMessage}");
                }
            });

            _client.MessageReceived.Subscribe(msg =>
            {
                if (_onMessage != null)
                {
                    Task.Run(() => _onMessage(msg.Text));
                }
            });

            await _client.Start();
        }
Example #23
0
        public LoRaWebSocket()
        {
            _context = new ApplicationDbContext();

            var factory = new Func <ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(5),
                    }
                };
                return(client);
            });

            //Url could be placed in appSettings json
            var url = new Uri("wss://iotnet.teracom.dk/app?token=vnoSywAAABFpb3RuZXQudGVyYWNvbS5ka2rsDK-oV3FsspLZBx8Hh9k=");

            client = new WebsocketClient(url, factory);
        }
Example #24
0
        public async Task <bool> Connect()
        {
            try
            {
                Client = new WebsocketClient(new Uri(Settings.Instance.PubSettings.Uri), WebSocketFactory)
                {
                    Name                  = "PubSub",
                    ReconnectTimeout      = TimeSpan.FromSeconds(5),
                    ErrorReconnectTimeout = TimeSpan.FromSeconds(5)
                };

                PubSubPingTimer = new Timer(new TimerCallback(SendingPing), Client, 0, 5000);
                await Client.Start();

                Subscribe();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #25
0
        public async Task <IWebsocketClient> InitAsync()
        {
            if (_logger.IsInfo)
            {
                _logger.Info($"Starting ETH stats...");
            }
            var url = new Uri(_webSocketsUrl);

            _client = new WebsocketClient(url)
            {
                ErrorReconnectTimeoutMs = _reconnectionInterval,
                ReconnectTimeoutMs      = int.MaxValue
            };
            _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);
                }
            });
            await _client.Start();

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

            return(_client);
        }
Example #26
0
        public CentrifugoClient(IWebsocketClient ws)
        {
            _ws = ws ?? throw new ArgumentNullException(nameof(ws));

            if (!_ws.Url.Query.Contains("format=protobuf"))
            {
                throw new NotSupportedException("формат общения Json не поддерживается. Используйте ?format=protobuf.");
            }
            _ws.IsTextMessageConversionEnabled = false;
            _connectedEvents = _connectedEventSource;
            _messageEvents   = _messageEventsSource;
            _errorEvents     = _errorEventsSource;

            //_pingEventsSource
            //    .Concat(Observable.Interval(TimeSpan.FromSeconds(10)))
            //    .SubscribeAsync(PingAsync);

            _operations = new ConcurrentDictionary <uint, TaskCompletionSource <ByteString> >();
            _channels   = new ConcurrentDictionary <string, Subscription>();

            HandleConnection();
            HandleSocketMessages();
        }
Example #27
0
        /// <inheritdoc/>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _client = await _clientFactory.CreateClientAsync();

            _client.Name                  = "deCONZ";
            _client.ReconnectTimeout      = TimeSpan.FromMinutes(5);
            _client.ErrorReconnectTimeout = TimeSpan.FromSeconds(30);

            _client.ReconnectionHappened.Subscribe(info =>
            {
                if (info.Type == ReconnectionType.Initial)
                {
                    _logger.LogInformation($"Connecting to websocket: {_client.Url}");
                }
                else
                {
                    _logger.LogInformation($"Reconnecting to websocket: {_client.Url} - cause: {info.Type}");
                }
            });

            _client.DisconnectionHappened.Subscribe(info =>
            {
                _logger.LogWarning($"Websocket got disconnected - cause: {info.Type}");
            });

            _client.MessageReceived.Subscribe(async msg =>
            {
                _logger.LogInformation($"Message received: {msg}");
                var message = JsonConvert.DeserializeObject <Message>(msg.Text);

                // emit event so mqtt service will pick it up.
                await _mediator.Publish(new DeConzMessageEvent(message), cancellationToken);
            });

            _logger.LogInformation("Starting websocket client...");
            await _client.Start();
        }
 public void SetUp()
 {
     _mockWebSocket = MockRepository.GenerateMock<IWebsocketClient>();
     
 }
 public StompOverWebsocketConnection(IWebsocketClient websocketClient)
 {
     _websocketClient = websocketClient;
 }
 private Task SendStatsAsync(IWebsocketClient client)
 => _sender.SendAsync(client, new StatsMessage(new Messages.Models.Stats(true, true, false, 0,
                                                                         _peerManager.ActivePeers.Count, (long)20.GWei(), 100)));
 private Task SendPendingAsync(IWebsocketClient client, int pending)
 => _sender.SendAsync(client, new PendingMessage(new PendingStats(pending)));
 private Task SendHelloAsync(IWebsocketClient client)
 => _sender.SendAsync(client, new HelloMessage(_secret, new Info(_name, _node, _port, _network, _protocol,
                                                                 _api, RuntimeInformation.OSDescription, RuntimeInformation.OSArchitecture.ToString(), _client,
                                                                 _contact, _canUpdateHistory)));