HTML and CSS Reference
In-Depth Information
To t a k e s To m e t h i n g l i k e G To To g l e Wa v e — t h e n To w d e f u n c t r e a l -
time web-based email and collaboration tool—as an example,
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 con-
nected people as soon as the keystrokes 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. That's a lot of data for what
was essentially a single keypress.
With sockets, on the other hand, because the connection is
always open, you need only send the information about the key-
stroke, which would then be disseminated to all the connected
clients via the server, and only that single piece of information
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—around 10-20 bytes of data—making our applica-
tion much more responsive, with faster transfer around the con-
nected sessions.
The simple WebSocket API
The WebSocket 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 in Chapter 10
with the Messaging API and Web Workers using postMessage
and onmessage . Sockets work in almost exactly the same way.
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 a particularly 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 to the essential methods for creating the con-
nection, sending data down the socket, receiving, and closing
the socket. There's also an error handler and a state flag, which
tells our app if the socket is currently connecting, open, closing,
or closed. Once you've closed a socket, it can't be reopened, so
you'll need to create a new socket.
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
WebSocket protocol to your
existing setup. Using servers
like Node.js, I was able to get a
WebSocket server up and run-
ning in around 20 minutes.
Visit   http://remysharp.com/
slicehost-nodejs-websockets/
to see how I documented
the process.
 
Search WWH ::




Custom Search