internal long Parse(byte[] data) { if (WSMode) { // now parse WS protocol WebsocketPacket ws = new WebsocketPacket(); var pSize = ws.Parse(data, 0, (uint)data.Length); if (pSize > 0) { WSRequest = ws; return(0); } else { return(pSize); } } else { var rp = new HTTPRequestPacket(); var pSize = rp.Parse(data, 0, (uint)data.Length); if (pSize > 0) { Request = rp; return(0); } else { return(pSize); } } }
private void Sock_OnReceive(NetworkBuffer buffer) { if (sock.State == SocketState.Closed || sock.State == SocketState.Terminated) { return; } if (buffer.Protected) { return; } if (processing) { return; } var msg = buffer.Read(); if (msg == null) { return; } var wsPacketLength = pkt_receive.Parse(msg, 0, (uint)msg.Length); //Console.WriteLine("WSP: " + wsPacketLength); if (wsPacketLength < 0) { buffer.Protect(msg, 0, (uint)msg.Length + (uint)-wsPacketLength); return; } uint offset = 0; while (wsPacketLength > 0) { if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.ConnectionClose) { Close(); return; } else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.Ping) { var pkt_pong = new WebsocketPacket(); pkt_pong.FIN = true; pkt_pong.Mask = false; pkt_pong.Opcode = WebsocketPacket.WSOpcode.Pong; pkt_pong.Message = pkt_receive.Message; offset += (uint)wsPacketLength; Send(pkt_pong); } else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.Pong) { offset += (uint)wsPacketLength; } else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.BinaryFrame || pkt_receive.Opcode == WebsocketPacket.WSOpcode.TextFrame || pkt_receive.Opcode == WebsocketPacket.WSOpcode.ContinuationFrame) { totalReceived += pkt_receive.Message.Length; //Console.WriteLine("RX " + pkt_receive.Message.Length + "/" + totalReceived);// + " " + DC.ToHex(message, 0, (uint)size)); receiveNetworkBuffer.Write(pkt_receive.Message); offset += (uint)wsPacketLength; //Console.WriteLine("WS IN: " + pkt_receive.Opcode.ToString() + " " + pkt_receive.Message.Length + " | " + offset + " " + string.Join(" ", pkt_receive.Message));// DC.ToHex(pkt_receive.Message)); } else { Console.WriteLine("Unknown WS opcode:" + pkt_receive.Opcode); } if (offset == msg.Length) { // Console.WriteLine("WS IN: " + receiveNetworkBuffer.Available); OnReceive?.Invoke(receiveNetworkBuffer); return; } wsPacketLength = pkt_receive.Parse(msg, offset, (uint)msg.Length); } if (wsPacketLength < 0)//(offset < msg.Length) && (offset > 0)) { //receiveNetworkBuffer.HoldFor(msg, offset, (uint)(msg.Length - offset), (uint)msg.Length + (uint)-wsPacketLength); // save the incomplete packet to the heldBuffer queue buffer.HoldFor(msg, offset, (uint)(msg.Length - offset), (uint)(msg.Length - offset) + (uint)-wsPacketLength); } //Console.WriteLine("WS IN: " + receiveNetworkBuffer.Available); OnReceive?.Invoke(receiveNetworkBuffer); processing = false; if (buffer.Available > 0 && !buffer.Protected) { Sock_OnReceive(buffer); } }