HTML5 Guidelines for Web Developers

(coco) #1

234 Chapter 9—WebSockets


node.js does not yet contain a WebSocket server, but help is available on the In-
ternet. At http://github.com/miksago/node-websocket-server, you will find a
small library implementing the current specification of the WebSocket protocol
for the server. The three JavaScript files of the node-websocket-server are simply
copied into a subdirectory and loaded with the following lines:

var ws = require(__dirname + '/lib/ws'),
server = ws.createServer();

From this point on, the variable server contains a reference to the WebSocket
server object. We still need to specify a port for the server:

server.listen(8887);

To start the server, we call the JavaScript file with the node.js interpreter:

node mini_server.js

Our minimal WebSocket server is now running and accepts connections at port
8887. But that is all our server can do for the moment. A more sensible applica-
tion is developed in the following example, which we will use to investigate the
individual components in more detail.

9.2 Example: A Broadcast Server


For our first little example, we want to communicate with a WebSocket that
transmits entered text to all clients with an active connection to the socket. This
is not a real Internet chat application but is well suited to the purpose of testing
the interactivity of WebSockets. Figure 9.1 shows how four interconnected cli-
ents exchange messages with each other.
Free download pdf