Skip to main content

TCP Chat Server in Node.js

d.Hello all.

Today in this post, I am going to explain about how to use a "net" module in node.js and build a basic chat server.(i.e a TCP chat server)

For this, you need to use either telnet / netcat(nc).(I have tried it on netcat, simply google "netcat download")
(Dont worry about the script for now, i will upload it, just go through the tutorial to understand the concept)

So, lets begin,

first of all to use node "net" module , we need to import it in out script.

var net = require("net")

This will import the net module. Now moving ahead, we need to create a server. This is done by createServer  function(on simply Server function).

var server = net.createServer()

createServer has a callback whenever a client connects to a server.

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


The code inside the createServer() function is callback(Hope you have know about the callbacks / event driven programming). This gets called whenever, a client gets connected to a server.

Now there are various events that can occur but we will focus mainly on "data" , "close" events.

 // this gets called whenever a clients send the data

 // this gets called whenever a socket is closed i.e. connection is terminate

So a basic TCP server looks like,
var net = require('net');

var s = net.createServer(function(socket){
        console.log("data is received");
        console.log("socket closed");
        console.log("An error occurs");

we have create a server and binds it port 1234.

To use it, run the server fie( node tcp_server.js)

To create clients,, nc localhost 1234
just type anything and hit enter

You will see the "Data is received" on server [ as "data" events occurs ]

Then close the client window.

You will see "socket closed" on server [ as close event occurs]

and that's it.
if the above idea is clear, this is enough to create a basic chat server.

Just create an array to hold the participants, add the new members to the array as the new clients joins, removes them from array as they gets disconnected.

Code for a Very Basic TCP Chat Server.

var net = require("net");
var participant = []; // array of participanticpants
var current = -1;
var total_participants = 0;
var server = net.createServer(function(socket){
    for(var i=0;i<participant.length;i++){
        if(participant[i] == socket) continue;
        participant[i].write("A new particpant joined the chat\n");
        participant[i].write("Now there are total " +total_participants+" members\n");
        for(var i=0;i<participant.length;i++){
            if(participant[i] == socket) {
                current = i;
            participant[i].write(i+" says : "+data);
        var i = participant.indexOf(socket);
        for(var i=0;i<participant.length;i++){
            participant[i].write(i+" left the chat\n");
            participant[i].write("Now there are total " +total_participants+" members\n");
        //console.log("error cooured-->"+err)
// socket.close();   


Hope this will helps.
Just leave a comment as a feedback if you like the post.

You can also check our Microservices post
Introduction to Microservices


Post a Comment

Popular posts from this blog

What is MonGoDB??

Share on Google Plus Now a Days, we are hearing a lot about MongoDB.

So, in this post I will try to briefly introduce to MongoDB.

MonGoDB is "Non-Relational, JSON, Document Store".

Explaining in detail,

Non-Relational, --> The DB we use most like SQl, Oracle are Relational DBs(RDBMS). They do have the fixed schemas, lots of tables. So Non-relational in nothing like that.

JSON : (JavaScript Object Notation) : It is basically a document with information in the form of key value pair.

for example,


thats it. 
A simple JSON document where name and address are key
and "lorem" and "ipsum" are corresponding values.

So, MongoDB is the Non Relational database which stores information using DOCUMENT and that document is a JSON document.

MongoDB stores collections of documents.
(Consider the above exxample as collection  "Person"  with a document)(will elaborate it later more)

Need of MongoDB:
The Databases we use…

Login with Google Account to Website using OAuth2.0 with PHP / Javascript

This post have Complete Code for Login / Sign-in  with google Account  using PHP / Javascript with oAuth2.0

Basically today we have seen almost every website needs you to register yourself before you can post or take part in any discussions to the website. But it become a tedious task to register and login to many different sites. Solution is to provide the users the option to Login with existing Google / Facebook account as almost everyone have Facebook and Google account.

In this post, I am going to explain how to integrate the Google Login / Sign in  for your website.

Download Source Code

Live Demo

For this,  First you need to create your Client ID, Client Secret and your developer API key.

For this go to

Click on the button Create Project. A new window will open up like this :

Enter the Project name and submit on Create.

Wait for new seconds, the new page will open like this.

On the left menu, click on API & Auth and click on credentails. Then…