HTML and CSS Reference
newmsg.value = ""; // clear out the message entry box
Let's break down that code just a little bit. First we create the socket and point it at a
location on our server. The server URL in our example uses the “ws://” protocol, as
opposed to the more common “http://” you're familiar with. This signals the special
protocol that Web Sockets use between client and server.
Next, we set up two event listeners on our socket object: onmessage and onclose . The
onclose handler is self-explanatory—it is fired when the connection is closed.
The server-side implementation of this chat room demo is beyond the
scope of this chapter, but there are lots of tutorials and software projects
that make this very easy to implement in any of your favorite server-side
Such a chat room server just needs to implement basic send and receive
implementation, the server doesn't even need to persist the messages;
it can just publish each message out to the socket stream as it is received,
meaning that all clients that are currently connected see it.
Our onmessage handler receives a string of data (which in our example we expect to be
JSON) and parses it into a message object. The message object contains an array of one
or more messages (each one is just simple text). The handler loops through each mes-
sage, adding it to the chat log in the order received.
Lastly, the code sets up a click event handler on the “Send Message” button. When
clicked, the handler takes whatever has been typed into the text entry input and sends
it to the server, using the send(...) method.
Admittedly, this type of functionality is not at all new. Since the advent of Ajax, using
the XMLHttpRequest (“XHR”) object, developers have been sending and receiving data
between browser and server. Other approaches have included instantiating an invisible
Flash object and using Flash's socket communication capabilities.
However, it's quite inefficient in the XHR approach to establish a whole new connec-
tion for each piece of data you need to send from browser to server. It's similarly un-
desirable to instantiate a memory-heavy Flash instance to use socket communication.
So, Web Sockets are understandably a welcomed addition to the “HTML5 & Friends”
family of technologies.
The message sending and receiving in Web Sockets is like a sensible mix between XHR
and Web Workers, which we looked at in the previous recipe.