Realtime chat application using NodeJs and socket.io

Chat CSS Html NodeJs

In this article,we will be using Socket.io to build a full-stack, real-time chat application with chat rooms.

This will be a great project to learn how to put together full-stack apps, and how to create an app where the backend can communicate with the frontend in real-time.

Normally, using HTTP requests, the server cannot push data to the client in real-time. But using Socket.io, the server is able to push real-time information to the client about some events that happened on the server.

Here's what we'll be using to build this app:

  • FrontendHTML, CSS & JavaScript
  • BackendNode and Express (Express is a very popular NodeJS framework that allows us to easily create APIs and backends)
  • Realtime communicationSocket.io (see below!)

What is Socket.IO?

Socket.IO allows the server to push information to the client in real-time when events occur on the server.

Without Socket.IO, the client would have to make multiple polling AJAX calls to verify that the event has occurred on the server. For example, the client could use JavaScript to check for an event on the server every 5 seconds.

Socket.IO means that the client doesn't have to make multiple polling AJAX calls to verify if some event has occurred on the server. Instead, the server sends the info to the client as soon as it gets it. Much better. 👌

Project Structure :

node_modules
    // node packages
public 
   index.html
   style.css
   script.js
index.js
package.json
package-lock.json

Create a new directory, we can run the following command:

mkdir <project name>

then move into the newly created directory:

cd <project name>

then  run this command : 

npm init

and fill this information like this:

package name: (project name)
version: (1.0.0)
description:
entry point: (index.js) 
test command:
git repository:
keywords:
author:
license: (ISC) 

After creating the project install the node package run the command:

npm install --save express socket.io

install node dev dependencies package run command:

npm install --save-dev nodemon

Open the index.js file and add this code :

const express = require('express');

const socket = require('socket.io');


//App Setup

const PORT = 7589;

const app = express();

const server = app.listen(PORT, function () {

    console.log("Listening on port " + PORT);

    console.log(`http://localhost:${PORT}`);

});


//static files

app.use(express.static("public"));



//Socket setup


const io = socket(server);


io.on("connection", function (socket) {

    console.log("Made Socket connection");


    io.on("disconnect", function (socket) {

        console.log("Socket Disconnected", socket.id)

    });


    socket.on("chat", function (data) {

        console.log("chat data = == = ", data)

        io.sockets.emit('chat', data);

    })


    socket.on("typing", function (data) {

        socket.broadcast.emit('typing', data);

    })


    socket.on("logoff", function (data) {

        socket.broadcast.emit('logoff', data);

    })


    socket.on("user-left", function (data) {

        socket.broadcast.emit('user-left', data);

    })

})

Create index.html in public folder <project name>/public/index.html and add this code :

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="UTF-8" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <title>Socket.io Chat App</title>

        <link rel="stylesheet" href="./style.css" />

        <script src="https://cdn.socket.io/4.6.0/socket.io.min.js" integrity="sha384-c79GN5VsunZvi+Q/WObgk2in0CbZsHnjEqvFxC5DxHn9lTfNce2WW6h2pH6u/kF+" crossorigin="anonymous"></script>

    </head>

    <body>

        <div id="devhubspot-chat">

            <div id="chat-window">

                <div class="nav">

                    <p>Simple Chat App</p>

                </div>

                <div id="output"></div>

                <div id="feedback"></div>

            </div>

            <input id="handle" type="text" placeholder="Your Name" />

            <input id="message" type="text" placeholder="Please type message here..." />

            <button type="button" id="send">Send</button>

        </div>

        <script src="./script.js"></script>

    </body>

</html>

Create index.html in public folder <project name>/public/index.html and add this code :

h2{

    font-size: 18px;

    padding: 10px 20px;

    color: #413ee6;

}


#devhubspot-chat{

    max-width: 600px;

    margin: 30px auto;

    border: 1px solid #ddd;

    box-shadow: 1px 3px 5px rgba(0, 0, 0, 0.05);

    border-radius: 2px;

}

#chat-window{

    height: 400px;

    overflow: auto;

    background: #f9f9f9;

}


#output p{

    padding: 14px 0px;

    margin: 0 20px;

    border-bottom: 1px solid #e9e9e9;

    color: #555;

}


#feedback p{

    padding: 14px 0px;

    margin: 0 20px;

    color: #aaa;

}


#output strong{

    color: #413ee6;

}


label{

    box-sizing: border-box;

    display: block;

    padding: 10px 20px;

}


input{

    padding: 10px 20px;

    box-sizing: border-box;

    background: #eee;

    border: 0;

    display: block;

    width: 100%;

    background: #fff;

    border-bottom: 1px solid #eee;

    font-size: 16px;

}


button{

    background: #413ee6;

    color: #fff;

    font-size: 18px;

    border: 0;

    padding: 12px 0;

    width: 100%;

    border-radius: 0 0 2px 2px;

}


.nav{

    margin: 0;

    padding: 0;

    overflow: hidden;

    background: #413ee6;

    width: 100%;

    height: 55px;

    font-size: 22px;

}


.nav p{

    color: #fff;

    text-align: center;

    font-size: 18px;

    font-weight: bold;

}

Create index.html in public folder <project name>/public/index.html and add this code :

var socket = io.connect("http://localhost:7589/");

var logoffTimer;

var userList = [];


var message = document.getElementById('message');

var handle = document.getElementById('handle');

var btn = document.getElementById('send');

var output = document.getElementById('output');

var feedback = document.getElementById('feedback');

var clients = document.getElementById('clients');


var gettingOutTimer;



btn.addEventListener('click', function () {

    var rand = Math.floor((Math.random() * 1000) + 1);

    this.handle = (handle.value == '') ? 'Anonymous-' + rand : handle.value;


    if (userList.indexOf(this.handle) === -1) {

        userList.push(this.handle);

    }


    if (message.value == "") {

        alert("Please type your message");

        return;

    }

    handle.disabled = 'disabled';

    socket.emit('chat', {

        message: message.value,

        handle: this.handle

    });


    message.value = '';

    handle.value = this.handle;

});


message.addEventListener('keypress', function () {

    this.handle = (handle.value == '') ? 'Anonymous-' + rand : handle.value;

    clearTimeout(logoffTimer);

    logoffTimer = setTimeout(() => {

        socket.emit("logoff", {});

    }, 60 * 30);

    socket.emit('typing', this.handle);

});


//listen on event


socket.on('chat', function (data) {

    feedback.innerHTML = '';

    output.innerHTML += '<p><strong>' + data.handle + '</strong>: ' + data.message + '</p>';

});


socket.on('typing', function (data) {

    feedback.innerHTML = '<p><em>' + data + ' is typing...</em></p>';

});


socket.on('logoff', function (data) {

    feedback.innerHTML = "";

});


socket.on('user-left', function (data) {

    feedback.innerHTML = '<p><em>' + data + ' is left from chat </em></p>';

    clearTimeout(gettingOutTimer);


    gettingOutTimer = setInterval(() => {

        socket.emit("logoff", {})

    }, 60 * 30);

});


Output:

Chat CSS Html NodeJs
Comments

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.