A Simple NodeJs-based Chat Demo

I have written a few posts about NodeJs. (Albeit only as a way to demo some Project Euler solutions - until now).

Requirements for getting my code to run on your own machine is that you install nodejs and npm. With npm you should install express and socket.io.

This simple demo is split into four parts, in three files. A static index.html page, a client side js file, and then a server.js file which includes setup for express and socket.io. Express is a great framework for http servers, and socket.io is a cross browser WebSockets implementation with fallbacks for browsers that do not implement websockets.

The main part is server.js:

The first part is the setup of express. The line:

app.use(express.static(__dirname + '/../Public'));

serves static files from the public directory, where we place our index.html file.

Express uses a simple way to setup simple routes

//A simple action to set the counter
app.get('/sentCounter/set/:count', function(req, res){
    sentCounter = req.params.count;
    res.send('ok');
});

This route for example is used to set the sentCounter value to a value sent in as a url part. /sentCounter/set/200 would set the value to 200.

To setup socket.io, simply call its listen method with the express-server as an argument. Socket io then takes over all calls to urls starting with /socket.io/

The socket.io server gets an event everytime a client connects, disconnects and sends a message. The server can send messages to specific clients or broadcast to all clients (with an option to filter specific clients away).

My demo implementation also has a timed event, that sends a message to all connected clients every 20 seconds.

The html is all vanilla, with a script included: /socket.io/socket.io.js - this is the client side api of the socket.io library.

The last part is my client side js file, which sets some event handlers for the buttons in the html, and handles connect, disconnect, incomming messages, and sending messages from the textarea.

It pretty much straight forward. The interesting parts are

socket.on('message', function(data){});

Which is called every time the client receives a message.

and

socket.send(message);

Which sends a message (you can send json, if you need to send objects).

That's it - you can grab the complete demo at Github