Open In App

Web-Socket in Node

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:

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






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: 




<!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: 


Article Tags :