Open In App
Related Articles

Web-Socket in Node

Like Article
Save Article
Report issue

What is a Web Socket? 

WebSocket is a communication protocol enabling full-duplex communication, allowing simultaneous two-way communication between a user’s browser and the server. It establishes a continuous connection, enabling messages to be sent between the web server and browser at any time. Unlike traditional request/response formats, WebSocket facilitates server-initiated communication with the client. To implement WebSocket in NodeJS, the “” dependency needs installation. Additionally, installing the “express” module is essential for server-side applications.

 npm install --save
npm install express --save

Note: npm in the above commands stands for the node package manager, a place from where we install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies. 

here is an example of how to make a connection from the server-side to the client-side through which the server will be able to send data to the client. 

// make a connection with the user from server side
io.on('connection', (socket)=>{
console.log('New user connected');


  • Server-Side (Node.js):
    • Requires and configures necessary modules: express,, and http.
    • Creates an HTTP server using express and http.
    • Sets up a WebSocket connection using
    • Handles user connections, emits an initial message, listens for user messages, and handles disconnections.
  • Client-Side (HTML/JS):
    • Creates a simple HTML form with an input field and a submit button.
    • Includes the Socket.IO library using <script src="/"></script>.
    • Establishes a WebSocket connection with the server upon page load.
    • Logs a message on successful connection and sets up listeners for incoming messages.
    • Emits a ‘createMessage’ event when the form is submitted, preventing the default form behavior.
    • Logs messages from the server and disconnection events.
  • Communication Flow:
    • Server emits an initial ‘newMessage’ to the user upon connection.
    • User’s form submission triggers the emission of a ‘createMessage’ event to the server.
    • Server logs the incoming message from the user.
    • Both the server and user log disconnection events.
  • Routing:
    • Server responds to the root route (“/”) by sending the HTML file (client-side.html in this case).
  • Additional Notes:
    • The server-side script (app.js) and the client-side HTML are separated.
    • Console logs on both the server and client provide insights into the connection, messages, and disconnections.


Example: Below is the code example of the server side: 


const express = require('express');
const socketIO = require('');
const http = require('http')
const port = process.env.PORT || 3000
var app = express();
let server = http.createServer(app);
var io = socketIO(server);
// make connection with user from server side
    (socket) => {
        console.log('New user connected');
        //emit message from server to user
                from: 'jen@mds',
                text: 'hepppp',
                createdAt: 123
        // listen for message from user
            (newMessage) => {
                console.log('newMessage', newMessage);
        // when server disconnects from user
            () => {
                console.log('disconnected from user');
    (req, res) => {
        res.sendFile(__dirname + "/client-side.html");




Example: Below is the code example of the client side: 


<!DOCTYPE html>
<html lang="en" dir="ltr">
    <meta charset="utf-8">
<body class="chat">
    <form id='message-form'>
        <input name='message'
               type="text" placeholder="Message"
               autofocus autocomplete="off" />
        <button type="submit">Send</button>
    <script src="/"></script>
        var socket = io();
        // connection with server
        socket.on('connect', function () {
            console.log('Connected to Server');
        // message listener from server
            function (message) {
        // add event listener to form
                function (e) {
                    // prevent the form from submitting
                    // emit message from user side
                            to: 'john@ds',
                            text: document
        // when disconnected from server
        socket.on('disconnect', function () {
            console.log('Disconnected from server');



Last Updated : 14 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Similar Reads