HTML and CSS Reference
In-Depth Information
WebSocket Events
The WebSocket API is purely event driven. Your application code listens for events on
WebSocket objects in order to handle incoming data and changes in connection status.
The WebSocket Protocol is also event driven. Your client application does not need to poll
the server for updated data. Messages and events will arrive asynchronously as the server
sends them.
WebSocket programming follows an asynchronous programming model, which
means that as long as a WebSocket connection is open, your application simply listens
for events. Your client does not need to actively poll the server for more information. To
start listening for the events, you simply add callback functions to the WebSocket object.
Alternatively, you can use the addEventListener() DOM method to add event listeners
to your WebSocket objects.
A WebSocket object dispatches four different events:
As with all web APIs, you can listen for these events using on<eventname> handler
properties, as well as using the addEventListener(); method.
WebSocket Event: Open
Once the server responds to the WebSocket connection request, the open event fires and a
connection is established. The corresponding callback to the open event is called onopen .
Listing 2-4 illustrates how to handle the event when the WebSocket connection is
Listing 2-4. Sample Open Event Handler
// Event handler for the WebSocket connection opening
ws.onopen = function(e) {
console.log("Connection open...");
By the time the open event fires, the protocol handshake has completed and the
WebSocket is ready to send and receive data. If your application receives an open event,
you can be sure that a WebSocket server successfully handled the connection request and
has agreed to communicate with your application.
WebSocket Event: Message
WebSocket messages contain the data from the server. You may also have heard of
WebSocket frames, which comprise WebSocket messages. We'll discuss the concept of
messages and frames in more depth in Chapter 3. For the purposes of understanding
Search WWH ::

Custom Search