Monthly Archives: February 2012

A vertex colouring application in Node js

Standard

My first web application in Node js is an implementation of vertex colouring algorithm. Here the application is a graph colouring technique which takes a graph and provide a proper colour to each of nodes according to vertex colouring algorithm. Here the server side and client side program is implemented in javascript. The frontend consisting of HTML5 ,jquery ,javascript  .Client program consist of html5 canvas and we can draw a graph using javascript in the canavas.The program code is in one file which conatin both code of html5 and javascript.

 

 In this article i talk about only the server side programming using Node js .Node js is an open source ,low level ,evented ,nonblocking server side javascript.If you want to read more about Node js  please go to this link https://neethutv.wordpress.com/2012/02/27/a-simple-chat-server-in-node-js/   and come back. To create  this vertex colouring application we need following constraints :

  • We want to server web pages so need a HTTP server
  • Server need to answer differently to requests ,depending on the which URL the request was asking. So need some kind of router to map requests to request handlers
  • To fulfill the requests that arrive at the server and have been routed using the router ,need request handlers 
  • The  router also treat incoming post data such as here the adjacency list of the graph for input to colouring algorithm  and give it to the request handlers so need request data handling .Here request handlers mainly contain graph colouring algorithm.

So let us start our application.

A basic HTTP server

I create a main file called index.js  which is to start our application and server.js  where our HTTP server  code lives. Let us start with server module. Server.js conatin following code


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

function start(route ,handle) {
http.createServer(function (req, res) {

var pathname=url.parse(req.url).pathname;
console.log(pathname);
var body=route(handle ,pathname,res,req);
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
}
exports.start=start;

The first line requires the http module and  that with Node js and make it accessible through  the variable http:


var http =require('http');

Also we requires another module named as url. This module have utilities for URL resolution and parsing.

var url=require("url");

Making some code a module means we need to export those parts of its functionality that we want to provide to scripts that require our module. Here our main module is index.js so to load server module we need to add a line as in index.js a follows:

var server=require("./server");

For now our HTTP server need to export ,we add a function named start as in above program and export this function as:

exports.start=start;

The url module provide methods  which allow to parse pathname from url:


var pathname=url.parse(req.url).pathname;

Our application can now distinguish requests based on the URL path requested – this allows us to map requests to our request handlers based on the URL path using our (yet to be written) router.  Serever code contain another function named as route which will expalin later.

Route The Requests

We need to able to feed requested url and GET and POST parameter into our router, and based on this the router then need to decide which code to execute. So this is the third part of our application which will discuss later. Here is the code for router.js


function route(handle,pathname,res,req) {

console.log("About to route a request for " + pathname);
  if(typeof handle[pathname]==='function'){
      return handle[pathname](res,req);

  }else {

     console.log("No request handler found for " + pathname);
}
}

exports.route = route;

This code will explain later.

Routing to request Handlers

   Routing means we want to handle requests  to different URLs differently.In our application first we need a request for web page to draw a graph. And also we need another url which contain POST data, which is created after submitting the graph for colouring. Router is not the place actually  do something with the requests, Here requests are routed to request Handlers. Let us create a module called requestHandlers.js ,it is a placeholder function for every request handler and export these as methods of the module. Here  is the code is too big so you can refer my bitbucket repository.

requestHandlers.js  mainly contain two methods one is start which is to start the HTML page contain  canvas to draw graph. We can load this HTML page using a module named ‘fs’ in Node js. The code as follows ,


var fs=require('fs');

function start(res,req) {

console.log("Request handler 'start' was called.");

fs.readFile('index.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end()

});

return ;

}

But we need to pass the request handlers from our server into router, Here we have two handlers. Now we can use javascript object which are just collections of name/value pair ,and these values may be strings ,numbers ,functions. Here we use values as functions.We want to pass the list of requestHandlers as an object.Now let us start to look our main module index.js ,which contain following code

var server=require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}

handle["/"] = requestHandlers.start;
handle["/graph"] = requestHandlers.colour;

server.start(router.route, handle);

We can see that handle is a collection of requesthandlers,map urls to corresponding request handlers.So whenever ‘/’ this url enters then execute the start function which resides on requestHandlers.js. We can also map different url’s to same request handler.If ‘/graph’ url enters then the colouring function will perform and return the coloured values.Also we need to use the function route() in server module:
route(handle ,pathname,res,req);

In our server program we have add handle parameter to our start() function and pass the handle object on the route() callback as its first parameter.Now here is the time to explain router.js.We need to check if a request handler for the given pathname exists,and if it does simply call according function.Because we can access our request handler functions from our object just as we would access an element of an associative array, we have his nice fluent handle[pathname]();

Handling the requests

Our requestHandlers.js contain two function one is to load html page which contain canvas to draw graph. After completed the graph just send the adjacency list by jquery/ajax. Then click the submit button another url will created  named as ‘/graph’, and this are send through using jquery. Then when ‘/graph’ enters on server program it will  execute the colouring algorithm.

Algorithm keeps a set of colours and the ‘availability list’ of colours for each node. First it takes each node in the order. It then checks the adjacentcy list of that node. If the first node in the list is coloured, it deletes that colour from the availability list. Then takes the next node from the adjacentcy list and the process continues. Last assigns the first colour in the availability list. This ensures the algorithm to take smallest number of colours. Then return the result as:


res.write(JSON.stringify(value_color)) ;

Then we can see the coloured graph on our web page. To get the complete code please visit my bitbucket repository https://bitbucket.org/neethuedappal/vertex-colouring-algorithm-using-node-js/changeset/3ed8b6e1599c




  

Node js – Server Side JavaScript

Standard

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