HTML and CSS Reference
Whereas with sockets, because the connection is always open,
all you need to send is the keystroke, which would then be dis-
seminated to all the connected clients via the server, and only
that keystroke would be sent.
The data sent has gone from Ajax, which will be perhaps
200-300 bytes of data, to a socket connection, which will be
just a few bytes of data, perhaps around 10-20 bytes, which will
be much more responsive and faster to transfer around the con-
The simple Web Socket API
The Web Socket API is also exceptionally easy to work with. Cur-
rently browsers only support sending strings (with the exception
of Firefox and Web Workers), which we've seen with the Mes-
saging API and Web Workers using postMessage and onmessage .
Sockets work almost exactly the same.
This means that you can't (currently) send binary data—but I'd
argue that in the web world we're used to working with JSON
and it's not particularly a big deal to encode to JSON as the
messages come in from a socket since we're already doing it for
JSON Ajax requests.
The API is limited down to creating the connection, sending data
down the socket, receiving and closing the socket. There's also
an error handler and a state fl ag, for connecting, open, closing,
and closed. Once you've closed the socket, the socket is com-
pletely closed down and can't be reopened. So if you need to
reopen it, you need to create a new socket to go out.
Creating a new Web Socket is easy, and very much like a Web
Worker. The protocol of the URL must be ws:// but the rest of the
URL can be structured just as you would a normal URL to be:
var socket = new WebSocket('ws://myserver.com/tweets:8080/');
For this example, I'm only going to be listening to the messages
that come from the tweets URL. Each is a new tweet from Twit-
ter that my server has been set up to listen for ( Figure 10.4 ).
NOTE Regarding the
ws:// server protocol:
Writing about how to set up the
server side is beyond the scope
of this topic, but there are
already several libraries out in
the wild that can add the Web
Socket protocol. Using servers
like Node.js I was able to get a
Web Socket server up and run-
ning in around 20 minutes and
documented it online: http://