protected ConnectionCloseEventArgs GetConnectionCloseEventArgsFromPayload(byte[] payload) { if (payload.Length >= 2) { using (MemoryStream stream = new MemoryStream(payload)) { ushort code = BinaryReaderWriter.ReadUShortExactly(stream, false); try { WebSocketCloseCode closeCode = (WebSocketCloseCode)code; if (payload.Length > 2) { string reason = Encoding.UTF8.GetString(payload, 2, payload.Length - 2); return(new ConnectionCloseEventArgs(closeCode, reason)); } else { return(new ConnectionCloseEventArgs(closeCode, null)); } } catch (InvalidCastException) { _logger.Warning(this.GetType(), "Close code {0} not recognised", code); return(new ConnectionCloseEventArgs(WebSocketCloseCode.Normal, null)); } } } return(new ConnectionCloseEventArgs(WebSocketCloseCode.Normal, null)); }
private static uint ReadLength(byte byte2, Stream stream) { byte payloadLenFlag = 0x7F; uint len = (uint)(byte2 & payloadLenFlag); // read a short length or a long length depending on the value of len if (len == 126) { len = BinaryReaderWriter.ReadUShortExactly(stream, false); } else if (len == 127) { len = (uint)BinaryReaderWriter.ReadULongExactly(stream, false); const uint maxLen = 2147483648; // 2GB // protect ourselves against bad data if (len > maxLen || len < 0) { throw new ArgumentOutOfRangeException(string.Format("Payload length out of range. Min 0 max 2GB. Actual {0:#,##0} bytes.", len)); } } return(len); }