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.

i.e
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.

socket.on('data',function(data){
 // this gets called whenever a clients send the data
});

socket.on('close',function(){
 // this gets called whenever a socket is closed i.e. connection is terminate
});


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

var s = net.createServer(function(socket){
    socket.on('data',function(d){
        console.log("data is received");
    });
   
    socket.on('close',function(){
        console.log("socket closed");
    });
    socket.on("error",function(err){
        console.log("An error occurs");
    });
});
s.listen(1234);


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){
    participant.push(socket);
    total_participants++;
    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");
       
    }
    socket.on('data',function(data){
        for(var i=0;i<participant.length;i++){
            if(participant[i] == socket) {
                current = i;
                continue;
            }
            participant[i].write(i+" says : "+data);
        }
    });
    socket.on('close',function(){
        var i = participant.indexOf(socket);
        participant.splice(i,1);
        total_participants--;
        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");
        }
       
    });
    socket.on("error",function(err){
        //console.log("error cooured-->"+err)
    });
// socket.close();   
});

server.listen(1234);


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

Comments

Post a Comment

Popular posts from this blog

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

Login with Google Account using PHP with code 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. For this,  First you need to create your Client ID, Client Secret and your developer API key. For this go to https://developers.google.com/identity/sign-in/web/sign-in Click on the button Create Project. A new window will open up. Please select Create Project / or select already created Project. It will then ask for about type ...

How To Set Up Apache Virtual Hosts on Ubuntu

How to setup Virtual Host in Ubuntu 16 / Ubuntu 18 on localhost / local machine To run the website with host on localhost(With LAMP) becomes important in many cases. This blog post will demonstrate how to achieve this. Assuming you have LAMP already installed and reading the code from (/var/www/html) Follow the simple steps below Create the code base To Create the code, simply create a directory named localweb inside /var/www/html. Create a file index.php inside localweb directory Content of index.php file <?php  echo "Local Website"; ?> Now our code base is set, so we need to configure apache Go to apache directory cd  /etc/apache2/sites-available/ Create one file named localweb.conf with content <Directory /var/www/html/localweb/>     AllowOverride All </Directory> <VirtualHost *:80>     ServerAdmin admin@localweb.com     ServerName localweb.com   ...

ORCAM - Blind can read too.!!

ORCAM: The technology that was developed mainly with the aim – to help to help the visually impaired and blind regain the functionalities that were lost. Yeah. So now even visually impaired guys can get to know even the smallest written things just by pointing towards them, like the reading the book. Yes. Even those who are completely blind, can even read a book using ORCAM. SO what actually is ORCAM.????? A visual system with human like performance to help visually impaired people Here is a look towards ORCAM-See for yourself Search Results It is a simple device with a camera and earphone   that fits in the simple glasses   and uses the Text-to-speech technology to read the objects and sends the user in the voice format with the help of the earphone. The   OrCam device is able to identify thousands of objects, including the faces of loved ones, dogs, buses, newspaper text and store signs, all with the point o...