Node.js An introduction and simple chat application


nodejs
Node.Js
Node.js is an event based non-blocking asynchronous programming model runs on powerful V8 javascript engine.It is primary motive to provide powerful and scalable network based application. The network based applications often act upon any events that makes the javascript call back methods which is event driven by default perfectly fit in to the bill.

How NodeJs can build scalable application where java and others can’t?
In languages like java or PHP each request means create a thread which in tern have their own stack trace of minimum 2MB. So consider a typical server has 8GB RAM, it can server up to 4000 concurrent users at a time.When the concurrent user base grows you need to get more servers and technical issues involved to horizontally scale on a large system.

Node solves this issue by changing how a connection is made to the server. Instead of spawning a new OS thread for each connection (and allocating the accompanying memory with it), each connection fires an event run within the Node engine’s process. It all mean calling a call back method for Node.js. Node also claims that it will never deadlock, since there are no locks allowed, and it doesn’t directly block for I/O calls. Node claims that a server running it can support tens of thousands of concurrent connections.

Install Node.js
on linux machine, just download the latest version and do the following steps.

tar -zxf node-v0.6.5.tar.gz
cd node-v0.6.5
./configure
make
sudo make install

On windows, Download the latest version. Remember you need python and Miscrosoft visual Studio to be installed beforehand.

>tar -zxf node-v0.6.5.tar.gz
>cd node-v0.6.5
>vcbuild.bat release
[Wait 20 minutes]
>Release\node.exe
> process.versions
{ node: ‘0.6.5’,
v8: ‘3.6.6.11’,
ares: ‘1.7.5-DEV’,
uv: ‘0.6’,
openssl: ‘0.9.8r’ }
>

Sample Node.js Chat application

net = require("net");
var sockets = [];
var server = net.Server(function(socket) {
	sockets.push(socket);
	socket.on('data', function(data) {
		for(var i = 0; i < sockets.length; i++) {
			sockets[i].write(data);
		}
	});
	socket.on('end', function(){
		var i = sockets.indexOf(socket);
		sockets.splice(i,1);
	});


});
server.listen(8000);
Advertisements

One thought on “Node.js An introduction and simple chat application

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s