Now i have got a chance to learn a new technology known as node js . I have developed a simple chat server and a vertex colouring application in node js. Before we talk about chat server let’s take a moment about node js .
What is node js
If we working with javascript then we don’t need to worry about this name because node js is allow to run javascript code in backend. Node.js is a platform built on Chrome’s javaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Node js itself is a program that will have to be compiled and installed on our machine.Then we can use javascript to write programs that use API of node js and are executed through “node programname.js“. It is an event loop based instead of threads and is able to scale to millions of cuncurrent connections. There is many advantages that servers spend most of their time to wait I/O operations .Every I/O operation in Node js is asynchrounous meaning that server can continue to process incoming requests while the I/O operations taking place.Node js is working with call backs and non blocking I/O. Call back means any functions execute in node js program does work in the background after calling ,executing a call back function once it is done.
An Example : Web server.
When i have started to learn i just search many tutorial on the web about the node js and all are teach me how to write a basic HTTP web server in node js. At first we have to understand the Node js module system. There are many modules listed in the node js documentation. We need to load these modules by using require function. Here is a simple web server it says hello world.
var http=require('http');
http.createServer(function(request , response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
Here i just wrote working of HTTP server. Let us execute this script with Node js:
node server.js
Now open your browser and point it at http://localhost:8888/ . This should display a web page that says ‘Hello world’.
Let us analyze our program. The first line requires the http module and that with Node js and make it accessible through the variable http. We then call one of the functions of http module: createServer . This function return an object and this object has a method named listen ,it take the port number our Http server is listen on. Here we create a server and pass a function to the method creating it. Whenever our server receives a request, the function we passed will be called. Incoming request is handle the function which we called. This concept in Node js is called callback .
Here the callback function passed two parameters request and response. These are objects and we can use their methods to handle request and responses. Whenever a request is received ,it use the response.writeHead() function to send an HTTP status 200 and content-type in HTTP response header,and response.write() function send the text ‘hello world ‘ finally response.end() finish our response.
An practical example – simple chat server
Building a chat server in Node js is very easy. Node js is make easy to write event based network servers. We know that a chat server allows multiple clients connect to it . Each client can write messages that are then broadcast to all other users. Here is a simple program for a multichat server
net = require('net');
var sockets = [];
var s = net.Server(function(socket) {
sockets.push(socket);
socket.on('data', function(d) {
for (var i=0; i < sockets.length; i++ ) {
if(socket!=sockets[i]) {
sockets[i].write(d);
}
}
});
});
s.listen(8001);
Here is the flow of this simple program:
- When a socket connects ,append the socket object to an array
- When any client write to their connections ,then write data to all sockets except the client’s
The first line allow access to contents of net module :
var net =require(‘net’)
This module also contain a Server function ,let we can use it and also we will need a place to hold all client connections so that we can write all of them when write the data.So we use an array named as sockets.
var sockets=[];
Then the next line starts a code that detemine what happen when each client connects,
var s = net.Server(function(socket) {
The only argument we pass into the Server is a function that will called each time when a client connects to server.Inside this function add each socket to the array.
sockets.push(socket);
Then the next piece of code set up an event handler to dictate what happens when a client sends data.
for (var i=0; i < sockets.length; i++ ) {
if(socket!=sockets[i]) {
sockets[i].write(d);
}
}
The socket.on function registers an event handler with node so that it know what to do when certain events happens.Node js calls this particular event handler when data is received from the client.The structure of socket.on callis similar to the Server() call.Both of them we pass a function and the fucntion is called when something is happened.Call back approach is common in asynchronous networking frameworks.Here when any client send data to server ,this anonymous function is called and data is passed into the function. It iterates over the list of socket objects you have been accumulating and sends the same data to them all. Each client connection will receive the data.
To get the complete code visit my bitbucket repository as https://bitbucket.org/neethuedappal/node-js-programs/changeset/95a5ed2fee37