HTML and CSS Reference
In-Depth Information
Web Sockets require both the browser and the server to speak a stand-
ardized and agreed-upon protocol (much like HTTP is for normal web
pages). However, this protocol has undergone quite a lot of experimen-
tation and change as it has developed over the last couple of years.
While things are beginning to stabilize, Web Sockets are still quite vol-
atile, and you have to make sure that your server is speaking the most
up-to-date version of the protocol so that the browser can communicate
properly with it.
The WebSocket object instance has, similar to XHR, a readyState property that lets you
examine the state of the connection. It can have the following constant values:
{worker}.CONNECTING (numeric value 0)
Connection has not yet been established
{worker}.OPEN (numeric value 1)
Connection is open and communication is possible
{worker}.CLOSING (numeric value 2)
Connection is being closed
{worker}.CLOSED (numeric value 3)
Connection is closed (or was never opened successfully)
The events that a WebSocket object instance fires are:
open
Called when the connection has been opened
message
Called when a message has been received from the server
error
Called when an error occurs with the socket (sending or receiving)
close
Called when the connection is closed
For each of these events, you can add an event listener using addEventListener(...) ,
or you can set a corresponding handler directly on the worker object instance, including
onopen , onmessage , onerror , and onclose .
If Web Sockets are not supported, you'll need to provide some fallback functionality
for your application, or at least gracefully notify the user that his browser doesn't sup-
port the required functionality. Fortunately, there's a very easy way to do that.
Because consistent browser support for Web Sockets has been elusive, the best practice
suggestion for using Web Sockets is to use a library like Socket.io ( http://socket.io ) ,
which attempts to use Web Sockets if available, and falls back to a variety of other
techniques for communication if Web Sockets are not present.
 
Search WWH ::




Custom Search