Coders Packet

Real time chat application using Node JS, express JS, and socket.io

By Imran Wahid

This is a real-time chat application based on Node Js, Express JS, and Socket.io with a text and location sharing feature.

This is a real-time chat application based on Node Js, Express JS, and Socket.io. This web application lets users send their live location as well as any kind of text messages to the users connected to the server. I have written the backend in Node Js and the npm modules that have been used are 

1. Express Js( for creating servers ).

2. Socket.io ( for real-time data sharing between client and server).

3. Path ( for easier path manipulations ).

4. Heroku ( for deploying the application ).

I have used bootstrap 4.4 for the frontend portion. Click here to see the main front-end part of the application 

The above link basically contains the HTML code of the message container div that will be filled with all the messages and the sending options below the message container. Here the div with the class name "container" is the message container and the div element with the class name "send" contains the sending bar( a text box, a send button, and a location-sharing button). 

Click here to see the interface

Click on the above link to see how the interface looks like while users are chatting with each other. The picture depicts most of the functionalities of the application. 

 

Now let's come to the backend part 

I have used socket.io for real-time data sharing. If you open the attached zip file you'll find the index.js file which is the server-side javascript file and the client.js file contains client-side javascript code. In the index.js file 

const express=require('express');
const path=require('path');
const socket=require('socket.io');
const moment = require("moment");

const app=express();
const port=process.env.PORT || 8000; 
const server= app.listen(port,()=>
{
    console.log(`Listening to the port ${port}`);
});

I have selected the port number dynamically and with the help of the express module, I have created a server that is listening to the dynamic port number. Now I have made the server listen to all the socket connections. Now I will be describing all the events that is handled by the server

1. When a new user joins  the following code is executed 

socket.on('new-user-joined',name=>
    {
        users[socket.id]=name;
        socket.broadcast.emit('user-joined',name);
    });

It adds the new user's name in the global user array and triggers the "new-user-joined" event and emits the "user-joined" event to the client-side.

 

2. When a user sends a message  the following code is executed 

socket.on('send',message=>
    {
        socket.broadcast.emit('receive',{message:message,name:users[socket.id]});
    });

It receives the message as an argument from the particular socket connection and broadcasts the message to all the clients connected to the server.

 

3. When a user gets disconnected the following code is executed 

socket.on('disconnect',message=>
    {
        socket.broadcast.emit('left',users[socket.id]);
        delete users[socket.id];
    });

The code snippet is simply removing the user from the global user array and triggering the "left" event to all the clients connected to the server that this particular socket connection is broken. 

 

4. When a user wants to share his/her location the following code is executed 

socket.on('kothai',data=>
    {
        socket.broadcast.emit('get',{message:data,name:users[socket.id]});
    });

It is simply triggering the "get" event to all the clients that this particular socket connection has sent his/her location details. Let's see how a user is sending his /her location. 

button_two.addEventListener('click',(e)=>
{
    e.preventDefault();
    if(!navigator.geolocation)
    {
        return alert(`Your browser doesn't support geo-location privileges`);
    }
    navigator.geolocation.getCurrentPosition((position)=>
    {
        append_location({latitude:position.coords.latitude,longitude:position.coords.longitude},`You`,'right');
        socket.emit('kothai',{latitude:position.coords.latitude,longitude:position.coords.longitude});
        messageContainer.scrollTop=messageContainer.scrollHeight;
    });
});

So in the sending bar, there is a location sharing button whose class name s button_two. When a user clicks on the button the browser collects the current location details through the navigator.geolocation  service and we are simply selecting the latitude and the longitude from the JSON data (named "position"). Then we are emitting the event "kothai" to the server which on receiving sends the "get" event to the clients. The "get" event is constructing the query for the google maps API with the help of latitude and longitude and sending the link to all the clients. 

 

5. When a user is typing some message the following code is executed 

socket.on('typing',data=>
    {
        socket.broadcast.emit('still_typing',`${data} is typing a message...`);
    })

It is broadcasting the "still-typing" event to the clients. 

messageInput.addEventListener('keypress',(e)=>
{
    socket.emit('typing',name);
});

Actually, when a user starts typing in the message box it's adding a "keypress" event and emitting the "typing" event to the server. That's how the real-time typing progress is shown. 

That's all about the socket events in brief. 

The full source code can found from the Github link. 

https://github.com/ImranWahidCoder/Imu-s-Chat-App

 

Download project

Reviews Report

Submitted by Imran Wahid (Imu2018)

Download packets of source code on Coders Packet