HTML and CSS Reference
Web Sockets are one of the shiniest new APIs outside of the
realm of HTML5, but they're actually really important for some
of the real-time-based web applications that have emerged in
Web Sockets give you a bi-directional connection between your
server and the client, the browser. This connection is also real-
time and is permanently open until explicitly closed. This means
that when the server wants to send your client something, that
message is pushed to your browser immediately.
This is what Comet was aiming to achieve, and succeeding.
Comet is a way of creating a real-time connection to your server,
but it would do it using a variety of different hacks. Ultimately, if
none of these hacks work, it would eventually fall back down
to Ajax polling, which would constantly hit your server and that
doesn't scale up very well.
If you have a socket open, your server can push data to all
those connected sockets, and the server doesn't have to con-
stantly respond to inbound Ajax requests. This is the move
from polling to pushing, from reactive to proactive. This is what
Comet was achieving through hacks, and this is what Web Sock-
ets achieves natively in the browser.
NOTE If the browser
doesn't natively support
Web Sockets, there's always a
way using Flash. Hiroshi Ichikawa
has written a Flash-based shim
for Web Sockets that's available
Sockets solve latency of
Low latency is a massive benefi t of Web Sockets. Since your
socket is always open and listening, as soon as data is pushed
from the server, it just has to make its way to your browser, mak-
ing the latency exceptionally low in comparison to something
like an XMLHttpRequest -based Ajax request.
In theory, with Google Wave, if you have lots of people all in
the same document, and you're all typing, you want to send all
those keystrokes to all the connected people as soon as they
happen. However, if you're using vanilla Ajax to do that, you
would have to create a new XHR object every time a key is hit,
and every one of those requests will contain all the headers that
are sent with a normal XHR request, like the user agent string,
the referrer URL, the accepted content type, and so on. All of
this data for what was essentially only a keypress.