/// <summary> /// Encodes a websocket frame into a byte buffer to be sent through the network /// </summary> /// <param name="frame">Websocket frame to send</param> /// <param name="mask">Only client should mask the message</param> /// <returns>The encoded byte buffer</returns> public static byte[] EncodeFrame(WebSocketFrame frame, bool mask = false) { var buffer = frame.Data ?? new byte[0]; var length = 0; byte[] result; var index = 0; var lenBuf = new byte[0]; if (buffer.Length <= 125) { length = (mask) ? buffer.Length + 128 : buffer.Length; // op code + length + key + data result = new byte[1 + 1 + buffer.Length + (mask ? 4 : 0)]; index = 2; } else if (buffer.Length >= 126 && buffer.Length <= ushort.MaxValue) { length = (mask) ? 126 + 128 : 126; // op code + length + ushort length + key + data lenBuf = BitConverter.GetBytes((ushort)buffer.Length); if (BitConverter.IsLittleEndian) { lenBuf = lenBuf.Reverse().ToArray(); } result = new byte[1 + 1 + 2 + buffer.Length + (mask ? 4 : 0)]; Array.Copy(lenBuf, 0, result, 2, lenBuf.Length); result[2] = (byte)((buffer.Length >> 8) & 0xFF); result[3] = (byte)(buffer.Length & 0xFF); index = 4; } else { length = (mask) ? 127 + 128 : 127; // op code + length + ulong length + key + data result = new byte[1 + 1 + 8 + buffer.Length + (mask ? 4 : 0)]; lenBuf = BitConverter.GetBytes((ulong)buffer.Length); if (BitConverter.IsLittleEndian) { lenBuf = lenBuf.Reverse().ToArray(); } Array.Copy(lenBuf, 0, result, 2, lenBuf.Length); index = 10; } result[0] = (byte)(128 + frame.Code); result[1] = (byte)length; var key = (mask) ? new byte[] { 1, 2, 3, 4 } : new byte[] { 0, 0, 0, 0 }; if (mask) { for (int i = 0; i < key.Length; i++) { result[index + i] = key[i]; } index += 4; } for (int i = 0; i < buffer.Length; i++) { result[index + i] = (byte)(buffer[i] ^ key[i % 4]); } return(result); }