in Node nodejs ~ read.

Create A Chat App in Nodejs

In this blog we are going to talk about how to create a chat app using Nodejs.

Prerequisite

  1. Basic knowledge of JavaScript
  2. Basic knowledge of Nodejs
  3. At least version 6.10.* of Node installed

How it works

Most of people use Nodejs as a backend server handling requests and response. But Nodejs could be more than that, in this course we are going to use Nodejs's Net module to create a simple chat app.

Let's get started

Let's create a file called net.js like the following.

const server = require('net').createServer();

server.on('connection', socket => {  
  console.log('A client is connected');
  socket.write('Welcome new client!\n');
});

server.listen(8000, () => console.log('Server bound'));  

In here we are using net module from Nodejs itself to create a server. Then when there is a client connected to this server we are going to display some message and this server is listen on port 8000.

Let's test this app by first starting the server. Open a terminal and cd into this directory then run the following command to spin up the server.

node net.js.

You should see the message of "Sever bound" & "A client is connected".

Next let's create another terminal and connect to the server.

We are going to use Netcat to connect to the server. Just the following command in the new terminal.

nc localhost:8000

You will see the message of "Welcome new client!"

Next let's add two events to the app that allow clients to send message to our server and notify the server when they are disconnected.

Modify your code like the following.

const server = require('net').createServer();

server.on('connection', socket => {  
  console.log('A client is connected');
  socket.write('Welcome new client!\n');

  socket.on('data', data => {
    console.log('data is: ', data);
    socket.write('data is: ');
    socket.write(data);
  });

  socket.on('end', () => {
    console.log('Client disconnected');
  })
});

server.listen(8000, () => console.log('Server bound'));  

As you can see here we create two new events - data & end. data will run every time we got message from client. end will run every time a client disconnect from the server.

Restart your server and create a new client. Try to type in some text, it should replay back the same text back to you from server.

Improve the design

Next we are going to modify the code so that two connected clients can talk to each other.

Modify your code like the following.

const server = require('net').createServer();  
let counter = 0;  
let sockets = {};

server.on('connection', socket => {  
  socket.id = counter++;
  sockets[socket.id] = socket;

  console.log('A client is connected');
  socket.write('Welcome new client!\n');

  socket.on('data', data => {
    Object.entries(sockets).forEach(([, cs]) => {
      cs.write(`${socket.id}: `);
      cs.write(data);
    });
  });

  socket.on('end', () => {
    delete sockets[sockets.id];
    console.log('Client disconnected');
  })
});

server.listen(8000, () => console.log('Server bound'));  

First we create a counter variable to keep track of the number of connected clients. Next we create a sockets variable to hold the information regarding each client. Next we broadcast each message to each connected socket.

Next let's allow client to enter their name.

Modify your code like the following.

const server = require('net').createServer();  
let counter = 0;  
let sockets = {};

server.on('connection', socket => {  
  socket.id = counter++;

  console.log('A client is connected');
  socket.write('Please typr your name: ');

  socket.on('data', data => {
    if(!sockets[socket.id]) {
      socket.name = data.toString().trim();
      socket.write(`Welcome ${socket.name}!\n`);
      sockets[socket.id] = socket;
      return;
    }

    Object.entries(sockets).forEach(([key, cs]) => {
      if(socket.id == key) return;
      cs.write(`${socket.name}: `);
      cs.write(data);
    });
  });

  socket.on('end', () => {
    delete sockets[sockets.id];
    console.log('Client disconnected');
  })
});

server.listen(8000, () => console.log('Server bound'));  

Here we ask client's name first then store the value into sockets variable. Then we check whether the message is from the sender itself, if it is then we just return nothing. Otherwise we will send the message to the rest of the connected client.

Next let's add a timestamp to the chat app as well.

Modify your code like the following.

const server = require('net').createServer();  
let counter = 0;  
let sockets = {};

function timestamp() {  
  const now = new Date();
  return `${now.getHours()}: ${now.getMinutes()}`;
}

server.on('connection', socket => {  
  socket.id = counter++;

  console.log('A client is connected');
  socket.write('Please typr your name: ');

  socket.on('data', data => {
    if(!sockets[socket.id]) {
      socket.name = data.toString().trim();
      socket.write(`Welcome ${socket.name}!\n`);
      sockets[socket.id] = socket;
      return;
    }

    Object.entries(sockets).forEach(([key, cs]) => {
      if(socket.id == key) return;
      cs.write(`${socket.name} ${timestamp()}: `);
      cs.write(data);
    });
  });

  socket.on('end', () => {
    delete sockets[sockets.id];
    console.log('Client disconnected');
  })
});

server.listen(8000, () => console.log('Server bound'));  

As you can see above that we created a function called timestamp() which will display the current time for each message.

End

Thanks for reading this blog. Nodejs has been proved itself as really useful tool for a variety of tasks. And hope you guys can learn something from this short blog. If you have any opinions or ideas please leave it below. Thanks!

comments powered by Disqus