HTML and CSS Reference
In-Depth Information
this.buttonMask = 0;
// set first handler
this.readHandler = versionHandler;
}
The bindSocketHandlers() function sets up the WebSocket event handlers used
by this protocol client. The message handler does something interesting: it adds any
incoming data to the byte stream and calls the current read handler, then continues
calling the current read handler until that handler returns false . This function allows the
message handler to effectively loop over the incoming data and process any number of
messages. If there is a partial message left in the stream, it remains there until the socket
produces another message event. At that time, the read handler that last returned false
is called again. The presence of additional bytes might cause that handler to then return
true . Listing 6-5 shows the bindSocketHandlers() function.
Listing 6-5. The bindSocketHandlers() Function
var bindSocketHandlers = function($this, socket) {
socket.onopen = function(e) {
// Ignore WebSocket open event.
// The server will send the first message.
}
var stream = $this.stream;
socket.onmessage = function messageHandler(e) {
// Append bytes to stream.
stream.append(e.data);
// Read handler loop.
while($this.readHandler($this, stream)) {
// Do nothing.
}
}
socket.onclose = socket.onerror = function() {
console.log("Connection closed", arguments);
}
}
Each event handler expects a certain number of bytes to be able to read a complete
message. If there are fewer bytes in the incoming stream, the handler returns false ,
which puts the WebSocket message event handler back into a waiting state. If there are
enough bytes to read a complete protocol data message, the handler reads that many
bytes out of the stream, processes them, and returns true . Each handler can also set the
next handler variable before returning true .
In Listing 6-6, the versionHandler() function sets the readHandler variable to
numSecurityTypesHandler , because the next state the client enters reads a message
containing the number of security types supported by the server.
 
Search WWH ::




Custom Search