WebSockets are not as simple as you think...
- Beware of the following
- Resources
- Example payloads
- Server requesting the connection to close
- Client responding to server's request to close a connection
- Server responding with a CONNACK
- Notes
- WebSockets
- Base framing protocol
- Status code reference
- Opcode reference
- MQTT 3.1.1
- Table 2.1 - Control packet types
- Table 3.1 - Connect return code values
- AWS IoT
Beware of the following
- All payloads are wrapped in the Base Framing Protocol
- Payloads from the client to the server MUST have their mask bit set, MUST include a 32-bit mask value, and the payload MUST be XORed with the mask. This is to prevent very broken intermediate servers from interpreting the payloads and trying to cache them.
Resources
- WebSockets RFC - RFC6455
- Section 5.2 - Base Framing Protocol
- Section 11.8 - WebSocket Opcode Registry
- Section 7.4 - Status Codes
- Section 11.7 - WebSocket Close Code Number Registry
- MQTT version 3.1.1 OASIS standard
- Mozilla reference on writing a WebSocket server
Example payloads
Server requesting the connection to close
If a server sends a payload like this:
0x88 0x00It translates to this:
Which means that it wants to close the connection.
Client responding to server's request to close a connection
If a client sends a payload like this:
0000: 88 82 41 42 D9 21 42 AADecoding it with the base framing protocol looks like this:
The final raw payload is:
0x03 0xE80x03E8 is equal to 1000 in decimal. This value is the status code. This payload means the server requested to close the WebSocket and the client closed it and indicated that the transaction was complete.
Server responding with a CONNACK
If the server sends a payload like this:
0000: 82 04 20 02 00 00Decoding it with the base framing protocol looks like this:
Decoding the MQTT payload:
Notes
These notes below are taken directly from the standards documents. They are left here so they can be copied and pasted into the examples easily.
WebSockets
Base framing protocol
Status code reference
Opcode reference
MQTT 3.1.1
Table 2.1 - Control packet types
Table 3.1 - Connect return code values
AWS IoT
AWS IoT will upgrade a connection to a WebSocket connection if the headers look valid but will not actually validate the credentials and signature until a device tries to send some data over the connection.
You can validate this by replacing the entire X-Amz-Signature value in the URI to a single character (z for example) and the system will still respond with HTTP/1.1 101 Switching Protocols.