HTML and CSS Reference
In-Depth Information
After the handshake is successfully completed, all messages traverse the TCP connection in frames. Frames contain
a small amount of information, including the type of data, some metadata, and the data payload. Messages can be split
among multiple frames. The data from client to server are slightly transformed, using a masking key that is randomly
generated on each push. If the data are not masked, the server terminates the connection. Data from the server to the
client are not masked, but they would also cause the connection to be terminated if they were. The point is not to make
the data cryptographically indecipherable, but rather to make the output unpredictable and to avoid proxy poisoning.
In addition to data frames, there are several frame types that are mostly initiated in server or browser code. These
control frames include Close , Ping , and Pong . Ping and Pong frames are used for “heartbeat” behavior (testing that
the connection is still live). A Ping frame must be answered with a Pong frame so long as the connection is open. Pong
frames do not need to be answered, and they can be sent without a preceding Ping. Unless you are building a new
WebSocket library, you do not have to worry about generating your own control frames. A library will generally have its
own algorithm to determine when to generate Pings or Pongs and when to close a connection if a Ping goes unanswered.
The WebSocket API
The WebSocket interface is simple yet powerful; there are only six functions. The first two, send and close , are used to
send a message and close a connection. The other four— onopen , onmessage , onerror , and onclose —are callbacks to
be executed when a socket is opened, a message is received, an error is generated, and a socket is closed, respectively.
A small application-programming interface (API) is easier to learn and build on, and its size allows you to list the
signatures in just a couple of dozen lines of code, as shown in Listing 11-3.
Listing 11-3. WebSocket Interface Functions
enum BinaryType { "blob", "arraybuffer" };
[Constructor(DOMString url, optional (DOMString or DOMString[]) protocols)]
interface WebSocket : EventTarget {
readonly attribute DOMString url;
// ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSING = 2;
const unsigned short CLOSED = 3;
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;
// networking
attribute EventHandler onopen;
attribute EventHandler onerror;
attribute EventHandler onclose;
readonly attribute DOMString extensions;
readonly attribute DOMString protocol;
void close([Clamp] optional unsigned short code, optional DOMString reason);
// messaging
attribute EventHandler onmessage;
attribute BinaryType binaryType;
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
Search WWH ::

Custom Search