Open In App

Web-Socket in Node

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 “socket.io” dependency needs installation. Additionally, installing the “express” module is essential for server-side applications.

 npm install socket.io --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');
});

Approach:

  • Server-Side (Node.js):
    • Requires and configures necessary modules: express, socket.io, and http.
    • Creates an HTTP server using express and http.
    • Sets up a WebSocket connection using socket.io.
    • 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="/socket.io/socket.io.js"></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.

Server-Side:

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

Javascript




const express = require('express');
const socketIO = require('socket.io');
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
io.on('connection',
    (socket) => {
        console.log('New user connected');
        //emit message from server to user
        socket.emit('newMessage',
            {
                from: 'jen@mds',
                text: 'hepppp',
                createdAt: 123
            });
 
        // listen for message from user
        socket.on('createMessage',
            (newMessage) => {
                console.log('newMessage', newMessage);
            });
 
        // when server disconnects from user
        socket.on('disconnect',
            () => {
                console.log('disconnected from user');
            });
    });
 
app.get("/",
    (req, res) => {
        res.sendFile(__dirname + "/client-side.html");
    });
 
server.listen(port);


Output:

Client-Side:

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

HTML




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


Output: 



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