private static async void OnTickAsync(object state) { if (_ws != null && _ws.State != WebSocketState.Open) { return; } if (_sendCount == 1000) { _timer = new Timer(OnTickAsync, null, 30000, 1); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{DateTime.Now} Max Send Count Reached: {_sendCount}"); Console.ResetColor(); Console.WriteLine(""); _sendCount = 0; } if (await _ws.SendAsync(_sendCount + " | " + DateTime.Now.Ticks.ToString())) { _sendCount++; } else { Ws_OnSendFailed(null, "", new Exception("Send Returned False")); } }
public async void Start() { var socketOptions = new PureWebSocketOptions() { DebugMode = false, SendDelay = 100, IgnoreCertErrors = true, MyReconnectStrategy = new ReconnectStrategy(2000, 4000, 20) }; ws = new PureWebSocket("ws://" + _url + "/websocket", socketOptions); ws.OnStateChanged += Ws_OnStateChanged; ws.OnMessage += Ws_OnMessage; ws.OnClosed += Ws_OnClosed; ws.OnSendFailed += Ws_OnSendFailed; await ws.ConnectAsync(); Console.WriteLine("SENDING WEBSOCKET MESSAGE"); string[] s = new string[1]; s[0] = "1"; WebSocket.ConnectMsg c = new WebSocket.ConnectMsg() { msg = "connect", version = "1", support = s }; await ws.SendAsync(JsonConvert.SerializeObject(c)); Console.ReadLine(); ws.Dispose(true); await ws.ConnectAsync(); }
private async Task <bool> InitWs() { _ws = new PureWebSocket("wss://graphigostream.prd.dlive.tv", new PureWebSocketOptions { DebugMode = false, SubProtocols = new[] { "graphql-ws" } }); _ws.OnOpened += () => { _ws.SendAsync("{\"type\":\"connection_init\",\"payload\":{}}\t").Wait(); _ws.SendAsync("{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{\"streamer\":\"" + _blockchainName + "\"},\"extensions\":{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"916cddf76e8b906a0a39ed0d9ecb2e3b603733cd91ea69235da267084f63f8ad\"}},\"operationName\":\"StreamMessageSubscription\",\"query\":\"subscription StreamMessageSubscription($streamer: String!) {\\n streamMessageReceived(streamer: $streamer) {\\n type\\n ... on ChatGift {\\n id\\n gift\\n amount\\n recentCount\\n expireDuration\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatHost {\\n id\\n viewer\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatSubscription {\\n id\\n month\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatChangeMode {\\n mode\\n __typename\\n }\\n ... on ChatText {\\n id\\n content\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatFollow {\\n id\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatDelete {\\n ids\\n __typename\\n }\\n ... on ChatBan {\\n id\\n ...VStreamChatSenderInfoFrag\\n __typename\\n }\\n ... on ChatModerator {\\n id\\n ...VStreamChatSenderInfoFrag\\n add\\n __typename\\n }\\n ... on ChatEmoteAdd {\\n id\\n ...VStreamChatSenderInfoFrag\\n emote\\n __typename\\n }\\n ... on ChatTimeout {\\n id\\n ...VStreamChatSenderInfoFrag\\n minute\\n __typename\\n }\\n ... on ChatTCValueAdd {\\n id\\n ...VStreamChatSenderInfoFrag\\n amount\\n totalAmount\\n __typename\\n }\\n __typename\\n }\\n}\\n\\nfragment VStreamChatSenderInfoFrag on SenderInfo {\\n subscribing\\n role\\n roomRole\\n sender {\\n id\\n username\\n displayname\\n avatar\\n partnerStatus\\n badges\\n __typename\\n }\\n __typename\\n}\\n\"}}") .Wait(); }; _ws.OnMessage += OnWebsocketMessage; _ws.OnClosed += reason => { Events.FireOnDisconnect(); }; return(_ws.ConnectAsync().Result); }
public async Task Subscribe(SubscribeMessage message) { try { if (_socket == null) { return; } SignSubcribeMessage(ref message); var json = JsonConvert.SerializeObject(message); await _socket.SendAsync(json); } catch (Exception ex) { _onError.Invoke(this, ex); } }
/// <summary> /// Called by the timer to make activity. /// </summary> /// <param name="state">The state.</param> private static async void OnTickAsync(object state) { if (_ws.State != WebSocketState.Open) { return; } if (_sendCount == 1000) { _timer = new Timer(OnTickAsync, null, 30000, 1); await OutputConsole.WriteLineAsync($"{DateTime.Now} Max Send Count Reached: {_sendCount}\r\n", ConsoleColor.Red); _sendCount = 0; } if (await _ws.SendAsync($"{_sendCount} | {DateTime.Now.Ticks}")) { _sendCount++; } else { Ws_OnSendFailed(_ws, "", new Exception("Send Returned False")); } }
private void Socket_OnMessage(object sender, string message) { Log($"Received message: {message}"); OnMessage?.Invoke(this, message); if (message == "#1") { _ = _socket.SendAsync("#2"); return; } else if (message == "1") { _ = _socket.SendAsync("2"); return; } var dict = _options.Serializer.Deserialize <Dictionary <string, object> >(message); if (!dict.TryGetValue("data", out dynamic dataObject)) { return; } dict.TryGetValue("rid", out var tmpRid); dict.TryGetValue("cid", out var tmpCid); dict.TryGetValue("event", out var tmpStrEvent); var rid = Convert.ToInt64(tmpRid); var cid = Convert.ToInt64(tmpCid); var strEvent = (string)tmpStrEvent; switch (Parser.Parse(rid, strEvent)) { case Parser.ParseResult.IsAuthenticated: Id = dataObject["id"]; //_listener.OnAuthentication(this, (bool)((JObject)dataObject).GetValue("isAuthenticated")); bool hasChannels; using (_syncLockChannels.Lock()) hasChannels = Channels.Any(); if (hasChannels) { _ = SubscribeChannelsAsync(); } break; case Parser.ParseResult.Publish: HandlePublish(this, dataObject["channel"], dataObject["data"]); break; case Parser.ParseResult.RemoveToken: SetAuthToken(null); break; case Parser.ParseResult.SetToken: SetAuthToken(dataObject["token"]); break; case Parser.ParseResult.Event: if (HasEventAck(strEvent)) { HandleEmitAck(this, strEvent, dataObject, Ack(cid)); } else { HandleEmit(this, strEvent, dataObject); } break; case Parser.ParseResult.AckReceive: if (_acks.TryGetValue(rid, out var value)) { _acks.Remove(rid); if (value != null) { var fn = (AckCall)value[1]; if (fn != null) { dict.TryGetValue("error", out var err); dict.TryGetValue("data", out var dat); fn(this, (string)value[0], err, dat); } else { Console.WriteLine("Ack function is null"); } } } break; default: throw new ArgumentOutOfRangeException(); } }