HTML and CSS Reference
In-Depth Information
Listing 3-4. UTF-8 Text Encoding
case opcodes.TEXT:
payload = buffer.toString("utf8");
WebSocket frames sent upstream from browsers to servers are “masked” to obfuscate
their contents. The purpose of masking is not to prevent eavesdropping, but is intended
for an unusual security reason and to improve compatibility with existing HTTP proxies.
See Chapter 7 for further explanation of the sort of cross-protocol attacks that masking is
intended to prevent.
The first bit of the second byte of the frame header indicates whether the frame is
masked; the WebSocket Protocol requires that clients mask every frame they send. If there
is a mask, it will be four bytes following the extended length portion of the frame header.
Every payload received by a WebSocket server is first unmasked before processing.
Listing 3-5 shows a simple function that unmasks the payload portion of a WebSocket
frame given four mask bytes.
Listing 3-5. Unmasking the Payload
var unmask = function(mask_bytes, buffer) {
var payload = new Buffer(buffer.length);
for (var i=0; i<buffer.length; i++) {
payload[i] = mask_bytes[i%4] ^ buffer[i];
return payload;
After unmasking, the server has the original message contents: binary messages can
be delivered directly, and text messages will be UTF-8 decoded and exposed through the
server API as strings.
Multi-Frame Messages
The fin bit in the frame format allows for multi-frame messages or streaming of partially
available messages, which may be fragmented or incomplete. To transmit an incomplete
message, you can send a frame that has the fin bit set to zero. The last frame has the fin bit
set to 1, indicating that the message ends with that frame's payload.
The WebSocket Closing Handshake
We looked at the WebSocket opening handshake earlier in this chapter. In human
interactions, we often shake hands when first meeting. Sometimes we shake hands when
parting, as well. The same is the case in this protocol. WebSocket connections always
begin with the opening handshake, as that is the only way to initialize the conversation.
On the Internet and other unreliable networks, connections can close at any time, so it
is not possible to say that connections always end with a closing handshake. Sometimes
the underlying TCP socket just closes abruptly. The closing handshake gracefully closes
connections, allowing applications to tell the difference between intentionally and
accidentally terminated connections.
Search WWH ::

Custom Search