All about programming in GNU/LINUX

Guide on writing socket programs using NODEJS : A simple Server using NODE

Hi folks !!!!! Here goes one more simple tutorial on using NODEJS.I’ve been fascinated by the ease with which one could create TCP and HTTP servers using NODEJS.This post is special since its my 100th blog.Its been a great journey starting from september 2011 , i thank Vignesh Prabhu from FSMK for pursuing me very much to start writing a blog for which im very glad today on the occasion of writing my 100th blog post

we shall start by writing the simplest socket program , A NODEJS program which just opens up and listens on port 9225

var net = require('net'); //Load the module , net module provides all functionalities to write sockets in NODEJS

var server = net.createServer( function(conn) {

       //This is the event handler function which illustrates the action once the connection is established with client , nw the function is empty
}).listen(9225); //listens to port 9225

You can see use the command `netstat -ant’ and see the port 9225 listening

This is how the structure of a server program using NODEJS looks like

var net=require('net');
var server=net.createServer(function(conn){ 
	////write code here on want action you want to achieve once the connection is established with the client 
	conn.on('data',function(data) {
         //write code here on want action you want to achieve once the connection is established and data flows in from client 
	});
	conn.on('close',function(){
	//write code here on want action you want to achieve once the client closes his end of the connection
	});


} ).listen(9225); //use any valid port number for the server to listen

I believe the last part clearly illustrated the structure of a TCP server using NODEJS , now we’ll take a look a look at a sample code making use of the same structure illustrated above

var net = require('net');
var server = net.createServer( function() {
	console.log('Connection Established'); 
	conn.on('data',function(data) {
		console.log(data + 'from' + conn.remoteAddress +  ' ' +  conn.remotePort );
		conn.write('Thank you , data successfully accepted'); //writing bck to the client 
	
	});
	conn.on('close' , function() ( 
		console.log('Client Closed the connection');
	});
}).listen(9225);
	console.log('Listening to port 9225');
Advertisements

One response

  1. Pingback: Encrypted Client-server communication using Nodejs TLS module and OpenSSL | hackintoshrao

Leave a Reply

Fill in your details below or click an icon to log in:

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