HTML and CSS Reference
In-Depth Information
Figure 3-6 shows the required and optional headers. Some headers are strictly
required and must be present and precise for a WebSocket connection to succeed. Other
headers in this handshake are optional but allowed because the handshake is an HTTP
request and response. After a successful upgrade, the syntax of the connection switches
over to the data-framing format used to represent WebSocket messages. Connections
will not succeed unless the server responds with the 101 response code, Upgrade header,
and Sec-WebSocket-Accept header. The value of the Sec-WebSocket-Accept response
header is derived from the Sec-WebSocket-Key request header and contains a special key
response that must match exactly what the client expects.
Computing the Key Response
To successfully complete the handshake, the WebSocket server must respond with a
computed key. This response shows that the server understands the WebSocket Protocol
specifically. Without the exact response, it might be possible to dupe some unsuspecting
HTTP server into upgrading a connection accidentally!
This response function takes the key value from the Sec-WebSocket-Key header sent
by the client and returns the computed value that the client expects in the returning
Sec-WebSocket-Accept header. Listing 3-3 uses the Node.js crypto API to compute the
SHA1 hash of the combined key and suffix:
Listing 3-3. Computing the Key Response Using the Node.jspto API Crypto API
var KEY_SUFFIX = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
var hashWebSocketKey = function(key) {
var sha1 = crypto.createHash("sha1");
sha1.update(key + KEY_SUFFIX, "ascii");
return sha1.digest("base64");
}
The kEY_SUFFIX in listing 3-3 is a constant key suffix included in the protocol
specification that every WebSocket server must know.
Note
In the WebSocket opening handshake and computing the key response, the
WebSocket protocol relies on Sec- headers that are defined in RFC 6455. Table 3-2
describes these WebSocket Sec- Headers.
 
 
Search WWH ::




Custom Search