protected bool HandleMessage(Message message) { lock (Sync) switch (message.Opcode) { case 1: OnString?.Invoke(Encoding.UTF8.GetString(message.Payload)); return(true); case 2: OnBinary?.Invoke(message.Payload); return(true); case 8: if (message.Length < 2) { FinishClose(); return(true); } ushort code = (ushort)(message.Payload[0] * 256 + message.Payload[1]); string reason = Encoding.UTF8.GetString(PrimitiveBuffer.Slice(message.Payload, 2, message.Length)); if (RecvClose && message.Length > 2) { return(false); } if (message.Length > 2) { return(FinishClose(code, reason)); } return(FinishClose(code)); case 9: OnPing?.Invoke(message.Payload); return(true); case 10: OnPong?.Invoke(message.Payload); return(true); default: return(false); } }
private static void HandleMessage(string msg) { if (msg.Equals("PONG", StringComparison.Ordinal)) { OnPong?.Invoke(); } }
private void OnIncomingMessage(Message message) { if (State == TcpSocketState.Closed) { return; } switch (message.Opcode) { case 1: string str; try { str = Encoding.UTF8.GetString(message.Data); } catch (ArgumentException) { ForciblyClose(); return; } OnString?.Invoke(str); break; case 2: OnBinary?.Invoke(message.Data); break; case 8: ushort code = (ushort)(message.Data.Length == 0 ? 0 : message.Data[0] * 256u + message.Data[1]); string reason = message.Data.Length >= 2 ? Encoding.UTF8.GetString(message.Data, 2, message.Data.Length - 2) : null; OnClose?.Invoke(code, reason); AnswerClose(code, reason); break; case 9: OnPing?.Invoke(message.Data); AnswerPing(message.Data); break; case 10: OnPong?.Invoke(message.Data); break; default: ForciblyClose(); break; } }
protected override void OnReceived(byte[] data) { if (!_isHandSharked) { _cache.AddRange(data); try { var handShakeText = Encoding.UTF8.GetString(_cache.ToArray()); string key = string.Empty; Regex reg = new Regex(@"Sec\-WebSocket\-Accept:(.*?)\r\n"); Match m = reg.Match(handShakeText); if (string.IsNullOrEmpty(m.Value)) { throw new Exception("回复中不存在 Sec-WebSocket-Accept"); } key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Accept:(.*?)\r\n", "$1").Trim(); _isHandSharked = true; } catch (Exception ex) { OnError.Invoke(UserToken.ID, ex); } } else { var coder = (WSCoder)UserToken.Unpacker; coder.Unpack(data, (d) => { var wsProtocal = (WSProtocal)d; switch (wsProtocal.Type) { case (byte)WSProtocalType.Close: base.Disconnect(); break; case (byte)WSProtocalType.Pong: var date = DateTime.Parse(Encoding.UTF8.GetString(wsProtocal.Content)); OnPong?.Invoke(date); break; case (byte)WSProtocalType.Binary: case (byte)WSProtocalType.Text: case (byte)WSProtocalType.Cont: OnMessage?.Invoke((WSProtocal)d); break; case (byte)WSProtocalType.Ping: ReplyPong(); break; default: var error = string.Format("收到未定义的Opcode={0}", d.Type); break; } }, null, null); } }
private async void Listen() { using (Stream ns = Stream) { WebSocketReader reader = new WebSocketReader(); OnHandshake?.Invoke(this, new HandshakeEventArgs(null, null)); while (Running && !ListenToken.IsCancellationRequested) { WebSocketFrame frame = await reader.Read(ns, null); if (frame == null || frame.Opcode == WebSocketOpcode.ConnectionCloseFrame) { Remove(WebSocketDisconnection.Disconnect); break; } switch (frame.Opcode) { case WebSocketOpcode.PingFrame: if (frame.Data.Length <= 125) { await Writer.WritePong(frame); OnPing?.Invoke(this, new PingEventArgs(frame.Data)); } break; case WebSocketOpcode.PongFrame: OnPong?.Invoke(this, new PongEventArgs(frame.Data)); break; case WebSocketOpcode.BinaryFrame: if (frame.Data.Length == 4 && frame.Data[0] == 22 && frame.Data[1] == 23 && frame.Data[2] == 24 && frame.Data[3] == 25) { await OnPingReceived(); } OnMessage?.Invoke(this, new MessageEventArgs(null, frame)); break; case WebSocketOpcode.TextFrame: OnMessage?.Invoke(this, new MessageEventArgs(null, frame)); break; } } } }
protected void OnReceived(byte[] data) { if (!_isHandSharked) { _isHandSharked = WSUserToken.AnalysisHandSharkReply(data); } else { var coder = (WSCoder)_wsContext.Unpacker; coder.Unpack(data, (d) => { var wsProtocal = (WSProtocal)d; switch (wsProtocal.Type) { case (byte)WSProtocalType.Close: _client.Disconnect(); break; case (byte)WSProtocalType.Pong: OnPong?.Invoke(Encoding.UTF8.GetString(wsProtocal.Content)); break; case (byte)WSProtocalType.Binary: case (byte)WSProtocalType.Text: case (byte)WSProtocalType.Cont: OnMessage?.Invoke((WSProtocal)d); break; case (byte)WSProtocalType.Ping: ReplyPong(); break; default: var error = string.Format("收到未定义的Opcode={0}", d.Type); break; } }, null, null); } }
internal void InvokePong(TimeSpan ms) { OnPong?.Invoke(this, ms); }
public void RaiseOnPong() { OnPong?.Invoke(DateTime.MinValue); }
public void FireEvent_OnPong(object source, NetworkPingPongArgs args) => OnPong?.Invoke(source, args);
private async Task ListenClient(WebSocketUser user) { using (Stream ns = user.Stream) { WebSocketReader reader = new WebSocketReader(); var res = await InterpretHeader(user, ns); if (!(res.Item1)) { RemoveClient(user, WebSocketDisconnection.NoHeader); return; } Logger.DebugWrite("INFO", $"Socket successfully handshaked the update. UID: {user.UID}"); OnHandshake?.Invoke(this, new HandshakeEventArgs(user, res.Item2)); while (Running && !user.ListenToken.IsCancellationRequested) { WebSocketFrame frame = await reader.Read(ns, user); if (frame == null || frame.Opcode == WebSocketOpcode.ConnectionCloseFrame) { RemoveClient(user, WebSocketDisconnection.Disconnect); break; } switch (frame.Opcode) { case WebSocketOpcode.PingFrame: if (frame.Data.Length <= 125) { await user.Writer.WritePong(frame); OnPing?.Invoke(this, new PingEventArgs(frame.Data)); } break; case WebSocketOpcode.PongFrame: OnPong?.Invoke(this, new PongEventArgs(frame.Data)); break; case WebSocketOpcode.BinaryFrame: user.Meta.LastTime.Binary = DateTime.UtcNow; if (RttEnabled && frame.Data.Length == 4 && frame.Data[0] == 26 && frame.Data[1] == 27 && frame.Data[2] == 28 && frame.Data[3] == 29) { OnPongReceived(user); } OnMessage?.Invoke(this, new MessageEventArgs(user, frame)); break; case WebSocketOpcode.TextFrame: user.Meta.LastTime.Text = DateTime.UtcNow; OnMessage?.Invoke(this, new MessageEventArgs(user, frame)); break; } } } }
private async Task ReadStream() { while (!Closing) { try { //try to read a header var hdata = new byte[24]; await Stream.ReadAsyncExact(hdata, 0, hdata.Length); var h = new MessageHeader(); h.ReadFromPayload(hdata, 0); if (h != null) { //read the payload var pl = new byte[h.PayloadSize]; await Stream.ReadAsyncExact(pl, 0, pl.Length); bool checksumOk = false; //verify hash using (var sha = SHA256.Create()) { var h1 = sha.ComputeHash(pl); var h2 = sha.ComputeHash(h1); checksumOk = h2[0] == h.Checksum[0] && h2[1] == h.Checksum[1] && h2[2] == h.Checksum[2] && h2[3] == h.Checksum[3]; } if (checksumOk) { switch (h.Command) { case "addr\0\0\0\0\0\0\0\0": { if (OnAddr != null) { var a = new Addr(); a.ReadFromPayload(pl, 0); await OnAddr?.Invoke(this, a); } break; } case "alert\0\0\0\0\0\0\0": { if (OnAlert != null) { var a = new Alert(); a.ReadFromPayload(pl, 0); await OnAlert?.Invoke(this, a); } break; } case "feefilter\0\0\0": { if (OnFeeFilter != null) { var f = new FeeFilter(); f.ReadFromPayload(pl, 0); await OnFeeFilter?.Invoke(this, f); } break; } case "filteradd\0\0\0": { if (OnFilterAdd != null) { var f = new FilterAdd(); f.ReadFromPayload(pl, 0); await OnFilterAdd?.Invoke(this, f); } break; } case "filterclear\0": { if (OnFilterClear != null) { var f = new FilterClear(); f.ReadFromPayload(pl, 0); await OnFilterClear?.Invoke(this, f); } break; } case "filterload\0\0": { if (OnFilterLoad != null) { var f = new FilterLoad(); f.ReadFromPayload(pl, 0); await OnFilterLoad?.Invoke(this, f); } break; } case "getaddr\0\0\0\0\0": { if (OnGetAddr != null) { var ga = new GetAddr(); ga.ReadFromPayload(pl, 0); await OnGetAddr?.Invoke(this, ga); } break; } case "getblocks\0\0\0": { if (OnGetBlocks != null) { var gb = new GetBlocks(); gb.ReadFromPayload(pl, 0); await OnGetBlocks?.Invoke(this, gb); } break; } case "getdata\0\0\0\0\0": { if (OnGetData != null) { var gd = new GetData(); gd.ReadFromPayload(pl, 0); await OnGetData?.Invoke(this, gd); } break; } case "getheaders\0\0": { if (OnGetHeaders != null) { var gh = new GetHeaders(); gh.ReadFromPayload(pl, 0); await OnGetHeaders?.Invoke(this, gh); } break; } case "headers\0\0\0\0\0": { if (OnHeaders != null) { var hd = new Headers(); hd.ReadFromPayload(pl, 0); await OnHeaders?.Invoke(this, hd); } break; } case "inv\0\0\0\0\0\0\0\0\0": { if (OnInv != null) { var iv = new Inv(); iv.ReadFromPayload(pl, 0); await OnInv?.Invoke(this, iv); } break; } case "mempool\0\0\0\0\0": { if (OnMemPool != null) { var mp = new MemPool(); mp.ReadFromPayload(pl, 0); await OnMemPool?.Invoke(this, mp); } break; } case "notfound\0\0\0\0": { if (OnNotFound != null) { var nf = new NotFound(); nf.ReadFromPayload(pl, 0); await OnNotFound?.Invoke(this, nf); } break; } case "ping\0\0\0\0\0\0\0\0": { if (OnPing != null) { var ping = new Ping(); ping.ReadFromPayload(pl, 0); await OnPing?.Invoke(this, ping); } break; } case "pong\0\0\0\0\0\0\0\0": { if (OnPong != null) { var pong = new Pong(); pong.ReadFromPayload(pl, 0); await OnPong?.Invoke(this, pong); } break; } case "reject\0\0\0\0\0\0": { if (OnReject != null) { var re = new Reject(); re.ReadFromPayload(pl, 0); await OnReject?.Invoke(this, re); } break; } case "sendheaders\0": { if (OnSendHeaders != null) { var sh = new SendHeaders(); sh.ReadFromPayload(pl, 0); await OnSendHeaders?.Invoke(this, sh); } break; } case "verack\0\0\0\0\0\0": { if (OnVerAck != null) { var va = new VerAck(); va.ReadFromPayload(pl, 0); await OnVerAck.Invoke(this, va); } break; } case "version\0\0\0\0\0": { if (OnVersion != null) { var v = new bitcoin_lib.P2P.Version(""); v.ReadFromPayload(pl, 0); await OnVersion?.Invoke(this, v); } break; } default: { //Console.WriteLine($"Got cmd: {h.Command}"); break; } } } else { Closing = true; } } } catch (Exception ex) { Closing = true; } } }
/// <summary> /// Zajmuje sie sprawdzaniem czy cos jest na gniezdzie, wczytywaniem naglowka /// oraz calych pakietow /// </summary> private void go() { try { GaduPacketHeader header = new GaduPacketHeader(); // naglowek while (true) { if (!tcpClient.Connected || tcpClient.GetStream().DataAvailable == false || work == false) { // jezeli na gniezdzie nie ma 8 pelnych bajtow lub gniazdo nie jest podlaczone to Thread.Sleep(sleepTime); // czekamy na nowe pakiety continue; // i przechodzimy do nastepnej iteracji } header.read(tcpClient.GetStream(), 8); // czytamy naglowek if (OnPacket != null) { OnPacket.BeginInvoke(header, null, null); } switch (header.Type) { case GaduPacketConstans.GG_RECV_MSG: // ktos przyslal nam wiadomosc GaduPacketRecieveMessage msg = new GaduPacketRecieveMessage(); msg.read(tcpClient.GetStream(), header.Length); // wczytujemy wiadomosc if (OnRecieveMessage != null) // jezeli ktos podstawil swoja funkcje pod event { OnRecieveMessage.BeginInvoke(msg, null, null); // to ja wywolujemy podstawiajac jako argument pakiet z wiadomoscia } break; case GaduPacketConstans.GG_SEND_MSG_ACK: // odebralismy pakiet potwierdzajacy wiadomosc GaduPacketMessageAck ack = new GaduPacketMessageAck(); ack.read(tcpClient.GetStream(), header.Length); // wczytaj pakiet if (OnRecieveMessageAck != null) { OnRecieveMessageAck.BeginInvoke(ack, null, null); // wywolaj event } break; case GaduPacketConstans.GG_PONG: // otrzymalismy pakiet GG_PONG z servera if (OnPong != null) { OnPong.BeginInvoke(null, null); } break; case GaduPacketConstans.GG_LOGIN_OK: // otrzymalismy pakiet informujacy nas o tym ze logowanie sie powiodlo if (header.Length == 1) { tcpClient.GetStream().ReadByte(); // jeden bajt, ktory nie zawsze musi sie pojawic, przeznaczenie nie poznane } if (OnLoginOK != null) { OnLoginOK.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_NEED_EMAIL: // server chce abysmy uzupelnili e-mail w naszych danych if (OnLoginNeedEmail != null) { OnLoginNeedEmail.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_LOGIN_FAILED: // logowanie sie nie powiodlo if (OnLoginFailed != null) { OnLoginFailed.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_NOTIFY_REPLY77: // otrzymalismy pakiet mowiacy o tym ze ktos zmienil status GaduPacketNotifyReplay77 gaduPacketNotifyReplay77; while (header.Length > 0) // najprawdopodobnie bedzie to zlepek pakietow, a wiec bedziemy je wczytywac po kolei { gaduPacketNotifyReplay77 = new GaduPacketNotifyReplay77(); gaduPacketNotifyReplay77.read(tcpClient.GetStream(), header.Length); header.Length -= gaduPacketNotifyReplay77.getSize(); if (OnGaduNotifyReplay != null) { OnGaduNotifyReplay.BeginInvoke(gaduPacketNotifyReplay77, null, null); // dla danego pakiety wywolaj event } } break; case GaduPacketConstans.GG_STATUS77: // ktos zmienil status na gg GaduPacketStatus77 gaduPacketStatus77 = new GaduPacketStatus77(); gaduPacketStatus77.read(tcpClient.GetStream(), header.Length); // wczytujemy pakiet if (OnGaduStatus != null) { OnGaduStatus.BeginInvoke(gaduPacketStatus77, null, null); // wywolujemny event } break; case GaduPacketConstans.GG_USERLIST_REPLY: GaduPacketUserListRequest gaduPacketUserlistReplay = new GaduPacketUserListRequest(); gaduPacketUserlistReplay.read(tcpClient.GetStream(), header.Length); if (OnUserListReplay != null) { OnUserListReplay.BeginInvoke(gaduPacketUserlistReplay, null, null); } break; case GaduPacketConstans.GG_PUBDIR50_REPLY: GaduPacketPubDir50 gaduPacketPubDir50 = new GaduPacketPubDir50(); gaduPacketPubDir50.read(tcpClient.GetStream(), header.Length); if (OnPubDirReplay != null) { OnPubDirReplay.BeginInvoke(gaduPacketPubDir50, null, null); } break; case GaduPacketConstans.GG_DISCONNECTING: if (OnGaduDisconnecting != null) { OnGaduDisconnecting.BeginInvoke(null, null); } break; case GaduPacketConstans.GG_DISCONNECTING2: if (OnGaduDisconnecting != null) { OnGaduDisconnecting.BeginInvoke(null, null); } break; default: // jezeli otrzymalismy jakis pakiet, ktory jeszcze nie jest obslugiwany przez biblioteke byte[] packet = new byte[header.Length]; for (int i = 0; i < header.Length; i++) // to wczytaj tylko pakiet z gniazda i nic z nim nie rob { packet[i] = (byte)tcpClient.GetStream().ReadByte(); } if (OnUnhandledPacket != null) { OnUnhandledPacket.BeginInvoke(header, packet, null, null); } break; } } } catch (ThreadAbortException) { // nie zadreczajmy uzytkownika tym wyjatkiem, w 99% powodowany przez Thread.Abort() } catch (Exception e) { if (Gadu.GaduCriticalError() == false) { throw new GaduRecieverException(e.Message); } } }
public async Task InvokePongAsync() { OnPong?.Invoke("pong received"); }
public void DoPong() { Thread.Sleep(1000); Console.WriteLine("Pong"); OnPong?.Invoke(); }