HTML and CSS Reference
var value = $("#message").val();
$("#output").append("<div>Sending: " + value + "</div>");
<input type='text' id='message'/>
Load up this file in a WebSocket-enabled browser, and you can send messages to the server, which it will
promptly echo back to you.
This code sets up a basic socket with the URI of the echo server and then adds callbacks that simply add a
message to a <div> with an ID of output whenever one of the four basic events is triggered.
It also adds a click handler to the Send button to send whatever message is typed. Because the server it con-
nects to is an echo server, any message sent should trigger a return message.
The preceding code covers using WebSockets on the client; on the server side you need a library that can
handle long-lived requests. This means that using a standard PHP or Ruby on Rails framework won't work.
Luckily your good friend Node works well with handling lots of concurrent connections.
As mentioned in the introduction, this chapter covers an abstraction on top of WebSockets called Socket.io
on the server side. If you want to use straight WebSockets, you can take a look at the Node ws module, available
This module enables you to create a WebSocket server in Node.js in a few lines of code and has syntax sim-
ilar to the browser WebSocket API.
Using Socket.io: WebSockets with
If you want to create a real-time game without the hassles of worrying about browser compatibility and fall-
backs, a number of libraries are available that can help, but one of the most popular and simplest to use is Sock-
et.io, available at http://socket.io .
Socket.io is a Node library that abstracts WebSockets and multiple supported fallbacks on both the client and
the server side. It also provides the capability to transparently send JSON data over sockets and adds support
for any number of custom events. Socket.io also integrates nicely into Express, which means you can use a
single app to serve your HTTP methods, your WebSockets, and your static files. Add in support for heartbeats,
timeouts, and disconnection support, and you see why using a library over straight WebSockets makes your life