public WebSocketFrame Read(Stream stream, Socket socket) { byte byte1; try { byte1 = (byte)stream.ReadByte(); } catch (IOException) { if (socket.Connected) { throw; } else { return(null); } } // process first byte byte finBitFlag = 0x80; byte opCodeFlag = 0x0F; bool isFinBitSet = (byte1 & finBitFlag) == finBitFlag; WebSocketOpCode opCode = (WebSocketOpCode)(byte1 & opCodeFlag); // read and process second byte byte byte2 = (byte)stream.ReadByte(); byte maskFlag = 0x80; bool isMaskBitSet = (byte2 & maskFlag) == maskFlag; uint len = ReadLength(byte2, stream); byte[] payload; // use the masking key to decode the data if needed if (isMaskBitSet) { byte[] maskKey = BinaryReaderWriter.ReadExactly(WebSocketFrameCommon.MaskKeyLength, stream); payload = BinaryReaderWriter.ReadExactly((int)len, stream); // apply the mask key to the payload (which will be mutated) WebSocketFrameCommon.ToggleMask(maskKey, payload); } else { payload = BinaryReaderWriter.ReadExactly((int)len, stream); } WebSocketFrame frame = new WebSocketFrame(isFinBitSet, opCode, payload, true); return(frame); }