// handle a websocket frame. Returns false if frame is continue, true otherwise private async Task <bool> HandleFrame(Frame frame) { // the frame is fragmented if (frame.Opcode == OpCode.Continue) { return(false); // return with pong } else if (frame.Opcode == OpCode.Ping) { await SendFrame(OpCode.Pong, frame.Data); // handle ping request by client } else if (frame.Opcode == OpCode.Pong) { if (pingQueue.Count > 0) { pingQueue.Dequeue()(frame.Data); } // client is requesting close, echo back and close connection } else if (frame.Opcode == OpCode.Close) { CloseFrame closeFrame = Framing.ParseClose(frame.Data); await SendFrame(OpCode.Close, frame.Data); client.Dispose(); // dispose the client (close the socket) if (server.GetClients().Contains(this)) { server.GetClients().Remove(this); } OnClose(closeFrame.Code, closeFrame.Reason); // handle text and binary data } else { OnMessage(frame.Data); } // packet was successfull handling return(true); }
public static CloseFrame ParseClose(byte[] data) { CloseFrame frame = new CloseFrame(); // parse code frame.Code = (data[0] & 0xff) << 8; frame.Code |= (data[1] & 0xff) << 0; // parse reason byte[] reason = new byte[data.Length - 2]; for (int i = 2; i < data.Length; i++) { reason[i - 2] = data[i]; } frame.Reason = Encoding.UTF8.GetString(reason); // return pased close frame return(frame); }