/// <summary> /// Prepare WebSocket send frame /// </summary> /// <param name="opcode">WebSocket opcode</param> /// <param name="mask">WebSocket mask</param> /// <param name="buffer">Buffer to send</param> /// <param name="offset">Buffer offset</param> /// <param name="size">Buffer size</param> /// <param name="status">WebSocket status (default is 0)</param> public void PrepareSendFrame(byte opcode, bool mask, byte[] buffer, int offset, int size, int status = 0) { // Clear the previous WebSocket send buffer WsSendBuffer.Clear(); // Append WebSocket frame opcode WsSendBuffer.Add(opcode); // Append WebSocket frame size if (size <= 125) { WsSendBuffer.Add((byte)((size & 0xFF) | (mask ? 0x80 : 0))); } else if (size <= 65535) { WsSendBuffer.Add((byte)(126 | (mask ? 0x80 : 0))); WsSendBuffer.Add((byte)((size >> 8) & 0xFF)); WsSendBuffer.Add((byte)(size & 0xFF)); } else { WsSendBuffer.Add((byte)(127 | (mask ? 0x80 : 0))); for (int i = 7; i >= 0; i--) { WsSendBuffer.Add((byte)((size >> (8 * i)) & 0xFF)); } } if (mask) { // Append WebSocket frame mask WsSendBuffer.Add(WsSendMask[0]); WsSendBuffer.Add(WsSendMask[1]); WsSendBuffer.Add(WsSendMask[2]); WsSendBuffer.Add(WsSendMask[3]); } // Resize WebSocket frame buffer int bufferOffset = WsSendBuffer.Count; WsSendBuffer.AddRange(new byte[size]); // Mask WebSocket frame content for (int i = 0; i < size; i++) { WsSendBuffer[bufferOffset + i] = (byte)(buffer[offset + i] ^ WsSendMask[i % 4]); } }
/// <summary> /// Clear WebSocket send/receive buffers /// </summary> public void ClearWsBuffers() { lock (WsReceiveLock) { WsReceived = false; WsHeaderSize = 0; WsPayloadSize = 0; WsReceiveBuffer.Clear(); Array.Clear(WsReceiveMask, 0, WsReceiveMask.Length); } lock (WsSendLock) { WsSendBuffer.Clear(); Array.Clear(WsSendMask, 0, WsSendMask.Length); } }