private void ParseMessage(dynamic response) { switch (response.type.ToString()) { case "ka": _isAlive = true; break; case "data": if (response.id.ToString().Contains("_chat")) { // Chat event BuildChatMessage(response.id.ToString(), response.payload.data.streamMessageReceived); } else { //Chest event BuildChestMessage(response.id.ToString(), response.payload.data.treasureChestMessageReceived); } break; default: //Unknown type Dlive.AddLogEntry(LogLevel.WARN, $"An unknown message was received, please report on GitHub at https://github.com/OfficialHisha/DSharp/issues/new: {response}"); break; } }
public void Connect() { if (IsConnected) { return; } byte[] messageBuffer = new byte[128]; _socket.ConnectAsync(Dlive.SubscriptionEndpoint, CancellationToken.None).Wait(); messageBuffer = Encoding.UTF8.GetBytes("{\"type\":\"connection_init\"}"); _socket.SendAsync(new ArraySegment <byte>(messageBuffer), WebSocketMessageType.Text, true, CancellationToken.None).Wait(); messageBuffer = new byte[128]; _socket.ReceiveAsync(new ArraySegment <byte>(messageBuffer), CancellationToken.None).Wait(); dynamic response = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(messageBuffer)); if (response.type.ToString() != "connection_ack") { string error = response.payload.message.ToString(); _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, error, CancellationToken.None).Wait(); OnError?.Invoke(error); Dlive.AddLogEntry(LogLevel.ERROR, $"The connection was refused by remote host with reason: {error}"); } Receive(); IsConnected = true; _isAlive = true; switch (Type) { case SubscriptionType.CHAT: SubscribeChat().Wait(); break; case SubscriptionType.CHEST: SubscribeChest().Wait(); break; case SubscriptionType.ALL: SubscribeChat().Wait(); SubscribeChest().Wait(); break; default: break; } OnConnected?.Invoke(); KeepAliveCheck(); }
private async Task KeepAliveCheck() { do { await Task.Delay(25000); if (!_isAlive) { Dlive.AddLogEntry(LogLevel.ERROR, $"Lost connection to remote host"); OnError?.Invoke("Lost connection to remote host"); OnDisconnected?.Invoke("Lost connection to remote host"); IsConnected = false; //Disconnect("Lost connection to remote host"); //Connect(); } _isAlive = false; } while (IsConnected); }