private static async Task SwitchUrl(WebsocketClient 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(); } }
void OnMessage(ResponseMessage message) { JsonNode payload = null; try { switch (message.MessageType) { case WebSocketMessageType.Binary: using (MemoryStream ms = new MemoryStream(message.Binary)) payload = JSON.ReadNodeFromStream(ms); break; case WebSocketMessageType.Text: payload = JSON.ReadNodeFromString(message.Text); break; default: return; } Logger.Info(this, $"payload: {payload}"); switch (payload.SelectValue <Opcode>("op")) { case Opcode.Dispatch: OnEvent(payload.SelectValue <string>("t"), payload.SelectValue <int>("s"), payload.SelectNode("d")); break; case Opcode.Hello: OnHello(payload.SelectSingle <int>("d/heartbeat_interval")); break; case Opcode.HeartbeatAck: missedheartbeats = 0; heartbeatacknowledged = true; break; case Opcode.InvalidSession: socket.Reconnect(); break; default: Logger.Warning(this, $"Unhandled discord opcode: {payload}"); break; } } catch (Exception ex) { Logger.Error(this, $"Unable to handle discord message: {payload}", ex); } }
public async Task Open(string url) { if (url.StartsWith("https")) { url = url.Replace("https", "wss"); } else if (url.StartsWith("http")) { url = url.Replace("http", "ws"); } if (client != null) { return; } client = new WebsocketClient(new Uri(url)); client.MessageReceived.Subscribe(OnMessageReceived); client.DisconnectionHappened.Subscribe(delegate(DisconnectionInfo info) { client.Reconnect(); }); client.ReconnectionHappened.Subscribe(delegate(ReconnectionInfo info) { Console.WriteLine(info.Type); }); await client.Start(); }
private async Task InitSocketAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); //TODO: add constructor with IOptionsMonitor with connection string _socket = new WebsocketClient(new Uri(_options.Value.ConnectionString)) { ReconnectTimeout = TimeSpan.FromSeconds(_options.Value.ReconnectionTimeout) }; _disconnectSubscriber = _socket.DisconnectionHappened.Subscribe(info => { _commandService.IsMaintenanceMode = true; _logger.LogError(info.Exception, $"{DateTime.UtcNow} Произошел дисконнект по сокету"); }); _socket.ReconnectionHappened.Subscribe(info => { _commandService.IsMaintenanceMode = false; _logger.LogInformation($"{DateTime.UtcNow} Вроде как переподключились"); _commandService.RefreshSubscriptions(); }); _commandSubscriber = _commandService.CommandSubject.Subscribe(command => { if (_socket.IsRunning) { _socket.Send(command.Command); } else { _logger.LogError($"{DateTime.UtcNow} Сокет в состоянии 'остановлен'"); } }, exception => { _logger.LogError(exception, "В процессе получения команд для отправки на биржу произошла ошибка"); }); _commandService.ReconnectIsNeeded.Subscribe((needReconnect) => { if (needReconnect) { _logger.LogInformation("Рестарт соединения через сокет"); _socket.Reconnect(); } }); _messageSubscriber = _socket.MessageReceived.Subscribe(message => { _processing.MessageHandler(message.Text); }, exception => { _logger.LogError(exception, "В процессе получения сообщений от биржи произошла ошибка"); }, () => { _logger.LogInformation("Остановка приема сообщений по сокету, по причине остновки источника"); }); await _socket.Start(); _commandService.IsMaintenanceMode = !_socket.IsRunning; }