Build real time notification using NodeJS and Socket.io

Node.js is the most popular platform to build real-time applications that run across distributed devices. In this article, i will show you how to build a simple notification system using socket.io.

http://www.unix-experience.fr/wp-content/uploads/2013/10/node-logo.png

socket.io is amazing library that allows us to use real-time technologies within every browsers (yes even with IE6). It uses one technology or another depending on the browser we are using, with the same interface for the developer. That’s means if we’re using Google Chrome we will use websockets, but if our browser does’t support them, socket.io will choose another supported transports. Definitely socket.io is the jQuery of the websockets. The supporter transports are:

  • WebSocket
  • Adobe Flash Socket
  • AJAX long polling
  • AJAX multipart streaming
  • Forever Iframe
  • JSONP Polling

I’ve applied this technology in our PYXIS system called PyxisNotif and currently running on production environment.

Back to today’s topic, first we create our node.js server. A really simple one.

 var http = require('http');
 var io = require('socket.io');
 server = http.createServer(function(req, res){
 });
 server.listen(8080);
 // socket.io
 var socket = io.listen(server);
 socket.on('connection', function(client){
 client.on('message', function(msg){
 socket.broadcast(msg);
 })
 });

This server will broadcast the message received from the browser to all connected clients.

Our HTML page will look like that:

 Comet Test

publish customAlert

publish customAlert2

As we can see we are including the js script called socket.io/socket.io.js. This script is served by our node server.

In fact we can use our node.js to serve everything (HTML, js, CSS) but in our example we will use only node.js for real-time stuff. Apache or NGINX will serve the rest of the code (only a HTML file in this case).

The example above show you how build a very simple notification using NodeJS and Socket.IO library. You can extend it on your own 🙂

Add a Comment

Scroll Up