Tutorials‎ > ‎

Message Broadcaster to Webpages using Node.js and Socket.io

posted Dec 28, 2011, 10:47 PM by Reza Aggi Prasetyo   [ updated Aug 15, 2016, 11:32 PM by Surya Wang ]

Introduction Welcome back to my article :)! In my previous article, I have given examples about hosting a simple web files on a Node server and making Node can log users in by reading file. This article uses the v0.5.9 of Node.js windows executable program that can be downloaded here.  

Installing Socket.io

Socket.io is a lightweight API that can help developers creating a Websocket application. Socket.io is an external module for Node.js server. So you need to install it first. Using Node.js windows version makes it not easy enough to install an external module of Node. You can follow the step of installing modules using npm here. I think there should be a way to use an external module of Node in Node.js windows version without installing it. I'll update the way here as soon as I find the way. :)  

Creating the Server

In this article, I made a new "Server.js" file to make the code simpler. So it will be different with the previous articles. Create a "Server.js" file, then insert this following code:
var http = require('http'), io = require('socket.io'); server = http.createServer(function (request, response) { try { console.log('Request from: ' + request.connection.remoteAddress + ' | href: ' + url.parse(request.url).href); response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end(); } catch (e) { sys.puts(e); response.writeHead(500); response.end('Internal Server Error'); } }).listen(8087, "", function () { console.log("Server running at http://localhost:8087/"); }); /* the socket.io code will be placed here */
var io = require('socket.io');
The code above means we load "socket.io" module into a variable named io.  

Code the socket!

Look at /* the socket.io code will be placed here */. Now let's code the socket in Server.js :) Thanks to Socket.io that has made developing websocket as easy as this.
var socket = io.listen(server); /* if a connection to socket happens */ socket.on('connection', function (client) { console.log('A client connected: ' + eval(client)); /* I made the server always reply with an object with attr 'type' and 'value' */ /* just to make code in client easier :) */ client.send('{ type: "response", value: true }'); /* if client sends a message */ /* because this is about broadcasting, so we won't use it at first */ client.on('message', function (data) { }); /* if client disconnected from socket */ client.on('disconnect', function () { console.log('A client disconnected: ' + eval(client)); }); }); /* here you can placed the code of broadcasting */ var index = 0; var quotes = ['"Moral indignation is jealousy with a halo." - H. G. Wells (1866-1946)', '"Glory is fleeting, but obscurity is forever." - Napoleon Bonaparte (1769-1821)', '"Don\'t stay in bed, unless you can make money in bed." - George Burns (1896-1996)', '"Don\'t be so humble - you are not that great." - Golda Meir (1898-1978) to a visiting diplomat', '"His ignorance is encyclopedic" - Abba Eban (1915-2002)', '"If a man does his best, what else is there?" - General George S. Patton (1885-1945)', '"Political correctness is tyranny with manners." - Charlton Heston (1924-2008)', '"There are no facts, only interpretations."- Friedrich Nietzsche (1844-1900)']; doQuote = function () { socket.broadcast('{ type: "message", value: "' + quotes[index] + '" }'); index = (index + 1) % 8; setTimeout(doQuote, 10000); };
  The detail of the following code above has been written in the comments. So I will only explain about the broadcasting. Socket.io helps us in broadcasting data to connected client via websocket using socket.broadcast() function. In the example above, I have an array of quotes that will be sent to clients continually every ten seconds using the setTimeout() function. Every data that this server sends to clients will be an object of "type" and "value" attributes. So the client will only need to check the "type" attribute to know what to do with the "value".  

Create the Client

First, we need to download and include the "socket.io.js" file for client or we can pull it from CDN:
<script type="text/javascript" src="http://cdn.socket.io/stable/socket.io.js"></script>
After that, we need to create a script that handle creating the connection to server and handling the data received from server via websocket. Create an "index.html" file and fill it with this following code:
<html> <head> <title>RZ - Broadcast Viewer</title> <script type="text/javascript" src="http://cdn.socket.io/stable/socket.io.js"></script> <script type="text/javascript"> function init() { var socket = new io.Socket('localhost', { port: 8087 }); if (socket.connect()) { /* a message received */ socket.on('message', function (data) { var msg = eval('(' + data + ')'); if (msg === 'response') { if (msg.value) { alert('connected to server!'); } } else if (msg === 'message') { /* put the message to container */ document.getElementById('broadcastContainer').innerHTML = msg.value; } else { alert('undefined type: ' + msg.type + ' with value: ' + msg.value); } }); /* if disconnected */ socket.on('disconnect', function () { alert('connection broken !'); }); } else { alert('error in creating connection to server !'); } } </script> </head> <body onload="init()"> <!-- the container of broadcasted message --> <div id="broadcastContainer"></div> </body> </html>
In the code above, we can see that every message that returned from server will be parsed from JSON string to an object using eval() function. The script will check the value of "type" attribute and do some work based on it. For example, if the "type" attribute is 'message', it will put the value of "value" attribute into a
with id "broadcastContainer". Every message broadcasted to client will be displayed in the container.  


Using this Socket.io as API of developing a web-based application that use websocket will be much easier. Even you can write a web-based chat application in a few rows.
Reza Aggi Prasetyo,
Dec 28, 2011, 10:47 PM