Subscribe via RSS Feed

Real-time Data update with Angular.js, Node.js and Socket.io

August 5, 2013 5 Comments

Current post is a proof of concept towards make a real time web application with Javascript based Web Server with Socket.IO with Angular.js and Node.js.

We have simulated a situation with 4 Product with their Best Buy Price, Best Sell Price and Last Trade Price.

bspbbp

To make this possible, we have selected -

1> Angular.js for client side development – Application Front End

2> Node.js for server side development

3> Socket.IO for Server and Client Communication.

4> Node.js Socket.IO module extention.

We have created a Proof of Concept with Javascript based web server Node.js, where we have focused on dealing with Socket.IO for real time application and angular.js on client side.

Architecture at a glance -

Angular.js NodeJS SocketIO

So here are the steps -

Installation -

A> Download and install Node.js from here.

B> To Develop the application we need to install socket.io module for Node.js

Command – npm install socket.io (should be connected to internet)

Configuration Code -

Now, we will try to describe the code portion -

 
var http = require('http');
var url = require('url');
var fs = require('fs');

// use socket.io
var io = require('socket.io').listen(server);

Here we have initialised the http, url and filesystem object within javascript variables in respect of Node.js concept.

Also we have initialised socket.io variable in the Node.js Environment.

server = http.createServer(function(req, res){ // Server creation
....
case '/angulartableRT.html':
            fs.readFile(__dirname + path, function(err, data){
                if (err){ 
                    return send404(res);
                }
                res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
                res.write(data, 'utf8');
                res.end();
            });	
....
server.listen(8001);
....

In the above code, we have shown some of the important part of node application.

In first section, we have written the creation of server via - http.createServer.

Next, we are giving access to the resources from the node.js server – “angulartableRT.html” for the client browser.

Now the server is listening on port 8001

Reader will get the whole code in GITHUB, which is linked at the end of Post.

Now the most important one is – socket.io communication from Node.js. We have commented below the node.js socket.io specific code.

 
// define interactions with client
io.sockets.on('connection', function(socket){ 
    //send data to client
    setInterval(function(){

		for(i=0;i<serverjson.length;i++) // A simulation of data from server instead of database calling
		{
			serverjson[i].BBP = Math.round((parseInt(serverjson[i].BBP) + Math.random())*100)/100;
			serverjson[i].BSP = Math.round((parseInt(serverjson[i].BSP) + Math.random())*100)/100;
			serverjson[i].LTP = Math.round((parseInt(serverjson[i].LTP) + Math.random())*100)/100;
		}

		var serverjsonstr = JSON.stringify(serverjson);

		socket.emit('msg', {'msg': serverjsonstr}); // Emitting Messages from Server 
		socket.emit('msgWrite', msgWrite);
    }, 1000);

});

Now run node server.js from command shell. This is our node.js specific code file.

Our sample application will be  - http://localhost:8001/
javascriptnosqlbook

Angular.js part -

Below is the code in Angular Controller and the Socket related code is discussed.

 
/* Controllers */
app.controller('StockListCtrl', function($scope, socket) { 
  $scope.stocks = [];
  socket.on('msg', function(data) { // Listening in Socket in Angular Controller
		$scope.stocks = JSON.parse(data.msg);

	});

});

//Getting value from server data change event
app.factory('socket', function($rootScope) {
	var socket = io.connect(); // Connection to the server socket
	return {
		on: function(eventName, callback) { // Return callback to the actual function to manipulate it.
			socket.on(eventName, function() { 
				var args = arguments;   
				$rootScope.$apply(function() {
					callback.apply(socket, args);
				});
			});
		}
	};
});

Angular HTML Binding

 <script src="http://localhost:8001/socket.io/socket.io.js"></script> // Important to know
 // Access socket.io.js from Angular.js 
.....

Below is the dynamic binding of Angular HTML with the Controller -

<body ng-controller="StockListCtrl">
     <div>
          <table class="table">
                ...
              <tbody>
                   <tr ng-repeat="stock in stocks"> <!-- Dynamic Binding of Angular Template with Data -->
                       <td>{{stock.Product}}</td>
                       <td>{{stock.BBP}}</td>
                       <td>{{stock.BSP}}</td>
                       <td>{{stock.LTP}}</td>
                   </tr>
              </tbody>
          </table>
     </div>
</body>

Reader can download the complete source-code in GitHub.

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner