'Encodes a WebSocket header.
:param fin: Whether this is the final frame for this opcode.
:param opcode: The opcode of the payload, see `OPCODE_*`
:param mask: Whether the payload is masked.
:param length: The length of the frame.
:param flags: The RSV* flags.
:return: A bytestring encoded header.'

@classmethod
def encode_header(cls, fin, opcode, mask, length, flags):

    first_byte = opcode
    second_byte = 0
    extra = ''
    result = bytearray()
    if fin:
        first_byte |= cls.FIN_MASK
    if (flags & cls.RSV0_MASK):
        first_byte |= cls.RSV0_MASK
    if (flags & cls.RSV1_MASK):
        first_byte |= cls.RSV1_MASK
    if (flags & cls.RSV2_MASK):
        first_byte |= cls.RSV2_MASK
    if (length < 126):
        second_byte += length
    elif (length <= 65535):
        second_byte += 126
        extra = struct.pack('!H', length)
    elif (length <= 18446744073709551615L):
        second_byte += 127
        extra = struct.pack('!Q', length)
    else:
        raise FrameTooLargeException
    if mask:
        second_byte |= cls.MASK_MASK
    result.append(first_byte)
    result.append(second_byte)
    result.extend(extra)
    if mask:
        result.extend(mask)
    return result
