public DataFragment(byte[] fragment) { _fragment = fragment; _head = (FragmentHead)_fragment[0]; Opcode = (FragmentOpcode)(_fragment[0] & _opcodeMask); Masked = (_fragment[1] & _maskFlagMask) != 0; _hasMaskingKey = Masked; CalculateLengthAndPositions(); }
public static DataFragment Create(byte[] payload, FragmentHead head, FragmentOpcode opcode, bool mask) { var payloadLength = payload.Length; var lengthBytes = new List <byte>(); if (payloadLength < 126) { lengthBytes.Add((byte)payloadLength); } else if (payloadLength < ushort.MaxValue) { lengthBytes.Add(126); var lbytes = BitConverter.GetBytes((ushort)payloadLength); if (BitConverter.IsLittleEndian) { Array.Reverse(lbytes); } lengthBytes.AddRange(lbytes); } else { lengthBytes.Add(127); var lbytes = BitConverter.GetBytes((ulong)payloadLength); if (BitConverter.IsLittleEndian) { Array.Reverse(lbytes); } lengthBytes.AddRange(lbytes); } byte[] maskingKey = new byte[0]; if (mask) { var rnd = new Random(); maskingKey = new byte[4]; rnd.NextBytes(maskingKey); ToggleMasking(payload, 0, maskingKey); lengthBytes[0] = (byte)(lengthBytes[0] + _maskFlagMask); } var bytes = new List <byte>(); bytes.Add((byte)((byte)head + (byte)opcode)); bytes.AddRange(lengthBytes); bytes.AddRange(maskingKey); bytes.AddRange(payload); return(new DataFragment(bytes.ToArray())); }