HTML and CSS Reference
In-Depth Information
WebSocket Event: Error
The
error
event fires in response to unexpected failures. The corresponding callback to
the
error
event is called
onerror
. Errors also cause WebSocket connections to close. If you
receive an error event, you can expect a close event to follow shortly. The code and reason in
the close event can sometimes tell you what caused the error. The
error event handler
is
a good place to call your reconnection logic to the server and handle the exceptions coming
from the WebSocket object. Listing 2-8 shows an example of how to listen for
error
events.
Listing 2-8.
Sample Error Event Handler
// Event handler for errors in the WebSocket object
ws.onerror = function(e) {
console.log("WebSocket Error: " , e);
//Custom function for handling errors
handleErrors(e);
};
WebSocket Event: Close
The
close
event fires when the WebSocket connection is closed. The corresponding
callback to the
close
event is called
onclose
. Once the connection is closed, the client
and server can no longer receive or send messages.
Not
■
The WebSocket specification also defines
ping
and
pong
frames that can be used
for keep-alive, heartbeats, network status probing, latency instrumentation, and so forth, but
the WebSocket API does not currently expose these features. Although the browser receives
a
ping
frame, it will not fire a visible
ping
event on the corresponding WebSocket. Instead,
the browser will respond automatically with a
pong
frame. However, a browser-initiated
ping
that is unanswered by a
pong
after some period of time may also trigger the connection
close
event. Chapter 8 covers WebSocket pings and pongs in more detail.
You also trigger the
onclose
event handler when you call the
close()
method and
terminate the connection with the server, as shown in Listing 2-9.
Listing 2-9.
Sample Close Event Handler
// Event handler for closed connections
ws.onclose = function(e) {
console.log("Connection closed", e);
};
The WebSocket
close
event is triggered when the connection is closed, which can
be due to a number of reasons such as a connection failure or a successful WebSocket
closing handshake. The WebSocket object attribute
readyState
reflects the status of the
connection (2 for closing or 3 for closed).
