Example #1
0
            /// <summary>
            /// Parse the header from the input stream.
            ///
            /// This will read bytes up to the start of the data block.
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static FrameHeader Parse(Stream input)
            {
                byte[] buffer = new byte[MaxHeaderSize];
                // Read the header
                if (!WebSocket.ReadBytes(input, buffer, 0, 2))
                {
                    return(null);
                }
                // Decode it
                FrameHeader header = new FrameHeader();

                header.Finished = ((buffer[0] & 0x80) == 0x80);
                header.OpCode   = (byte)(buffer[0] & 0x0f);
                header.Masked   = ((buffer[1] & 0x80) == 0x80);
                // Get the length
                long length = (long)(buffer[1] & 0x7f);

                // Check for extended length
                if (length == 126)
                {
                    // 16 bit payload length
                    if (!WebSocket.ReadBytes(input, buffer, 0, 2))
                    {
                        return(null);
                    }
                    length = ConvertBytes(buffer, 2);
                }
                else if (length == 127)
                {
                    // 64 bit payload length
                    if (!ReadBytes(input, buffer, 0, 8))
                    {
                        return(null);
                    }
                    length = ConvertBytes(buffer, 8);
                }
                header.Length = length;
                // If the frame is masked we need the key
                if (header.Masked)
                {
                    header.Key = new byte[KeySize];
                    if (!WebSocket.ReadBytes(input, header.Key, 0, KeySize))
                    {
                        return(null);
                    }
                }
                return(header);
            }