What is Socket.io

Socket.io is used to build chat application in node js and express js. socket.io use Web Socket to create bi-directional communication channel between client and server. Socket provides both client (socket.io.client) and server (socket.io) for chat application.

Install Socket.io

Socket.io is available on NPM. To install Socket.io, type following command.

npm i socket.io


Create an Express App

socket.io is build using Express JS in node js application. Install Express js in node application and follow steps below.

In the root folder, create a directory names src and add app.js file. Add following code in app.js file.

Chat Application

    /* app.js */

const express=require("express");
const app=express();
const http = require('http');
const server = http.createServer(app);

app.get("/",(req,res)=>{
    res.status(200).send(`<h1>Chat Application</h1>`);
});

server.listen(3000,()=>{
    console.log(`App running at http://127.0.0.1:3000`);
});
node src/app

Create html file

In the src folder, add a directory names public and add index.html file. Copy the code below and paste in index.html file.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<title>Socket.IO chat</title>
<meta charset="utf-8">
<style>
*{ 
    margin:0; 
    box-sizing:border-box;
}
body{ 
    padding-bottom: 3rem; 
    font-family: sans-serif;
}
    
#form { 
    background: rgba(0, 0, 0, 0.15); 
    padding: 0.25rem; 
    position: fixed; 
    bottom: 0; 
    left: 0;
    right: 0; 
    display: flex; 
    height: 3rem; 
    backdrop-filter: blur(10px);
}
#input{ border: none; 
    padding: 0 1rem; 
    flex-grow: 1; 
    border-radius: 2rem; 
    margin: 0.25rem; 
}
#input:focus{ outline: none; }
#form > button{ 
    background: #333; 
    border: none; 
    padding: 0 1rem; 
    margin: 0.25rem; 
    border-radius: 3px; 
    outline: none;
    color: #fff; 
}
    
#messages{ list-style-type: none; margin: 0; padding: 0; }
#messages > li { padding: 0.5rem 1rem; }
#messages > li:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
    <h1>Chat Application</h1>
    <ul id="messages"></ul>
    <form id="form" action="">
        <input aria-label="message" id="input" autocomplete="off" >
        <button>Send</button>
    </form>
</body>
</html>

add html file to app.js

Chat Application



    /* app.js */

const express=require("express");
const app=express();
const http = require('http');
const server = http.createServer(app);
app.use(express.static("src/public"));

    
app.get("/",(req,res)=>{
    res.sendFile(__dirname + '/index.html');
});
    
server.listen(3000,()=>{
    console.log(`App running at http://127.0.0.1:3000`);
});

node src/app


Integrate Socket.io

socket.io includes a server socket-io with nodejs application and a client library socket-io-client for client side application.

    /* app.js */  
const express=require("express");
const app=express();
const http = require('http');
const server = http.createServer(app);
app.use(express.static("src/public"));
app.use(express.static("node_modules/socket.io/client-dist/"));
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
  
io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});
  
server.listen(3000, () => {
    console.log('listening on *:3000');
});

Update index.html

    /* index.html */ 

<script src="socket.io.min.js"></script>

<script>
const socket = io();
</script>

node src/app


Emit Events

Now add submit event in index.html page. use e.preventDefault() to stop default action.

    /* index.html */ 
        
<script src="socket.io.min.js"></script>
        
<script>
const socket = io();

const form = document.getElementById('form');
const input = document.getElementById('input');

form.addEventListener('submit', function(e) {
    e.preventDefault();
    if (input.value) {
      socket.emit('chat message', input.value);
      input.value = '';
    }
});

</script>

Broadcast

In the final stage, broadcast message from client to server and server to client.

    /* app.js */  

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
});
    /* index.html */  
    
<script src="socket.io.min.js"></script>
            
<script>
const socket = io();
    
const form = document.getElementById('form');
const input = document.getElementById('input');
const messages = document.getElementById('messages');
    
form.addEventListener('submit', function(e) {
    e.preventDefault();
    if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
    }
});

socket.on('chat message', function(msg) {
    var item = document.createElement('li');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
  });
</script>    

node src/app

Test Chat Application

Now open the app in two different browsers, or Incognito mode. Type message on one window and check it on another window.


Source Code

Get the the complete source code of above application from my Github Repository


Chat Application in Node JS