Game Development Reference
In-Depth Information
The header mask indicates whether this packet is the final fragment of a message (messages can be split into
fragments), what the opcode is, and whether a mask is present. The payload length field plays double duty. For small
messages (less than 125 bytes), it holds the length of the message, but for messages that are longer, the payload
length is used as a flag to indicate the size of the extended payload length field. The extended payload length follows
immediately after the first 16 bits of the header (it comes before the mask). When payload length is equal to 126, the
extended payload length is 16 bits, and when it is equal to 127, the extended payload length is 64 bits.
WebSocket opcodes are split into three categories: continuation, non-control, and control. Continuation and
non-control opcodes indicate user messages, and control frames are used to configure the protocol itself. Presently
the following opcodes are defined as shown in Table 10-1 .
Table 10-1. WebSocket Opcodes
opcode
Meaning
0x0
Message continuation [continuation]
0x1
Text message [non-control]
0x2
Binary message [non-control]
0x8
Connection Close [control]
0x9
Ping [control]
0xA
Pong [control]
Once you have parsed the header, extracting the payload is trivial. Do not forget to XOR in the mask. Parsing the
header is made interesting by the fact that its size and layout are variable and thus cannot be mapped directly to a C
structure. However, because each WebSocket message is at least 16 bits, you can define a structure that only reserves
16 bits (a uint16_t) of storage, the optional header fields and payload of the message should immediately follow the
header in memory, see Listing 10-7.
Listing 10-7. The WebSocketMessageHeader
struct WebSocketMessageHeader {
union {
struct {
unsigned int OP_CODE : 4;
unsigned int RSV1 : 1;
unsigned int RSV2 : 1;
unsigned int RSV3 : 1;
unsigned int FIN : 1;
unsigned int PAYLOAD : 7;
unsigned int MASK : 1;
} bits;
uint16_t short_header;
};
size_t GetMessageLength() const;
size_t GetPayloadOffset() const;
size_t GetPayloadLength() const;
uint32_t GetMask() const;
 
Search WWH ::




Custom Search