How to send broadcast to all connected client in node js

16,144
var WebSocketServer = require("ws").Server;

var wss = new WebSocketServer({port:8100});

wss.on('connection', function connection(ws) {
    ws.on('message', function(message) {
       wss.broadcast(message);
    }

}

wss.broadcast = function broadcast(msg) {
   console.log(msg);
   wss.clients.forEach(function each(client) {
       client.send(msg);
    });
};
Share:
16,144
Darshan Soni
Author by

Darshan Soni

Android Developer

Updated on June 25, 2022

Comments

  • Darshan Soni
    Darshan Soni almost 2 years

    I'm a newbie working with an application with MEAN stack. It is an IoT based application and using nodejs as a backend.

    I have a scenario in which I have to send a broadcast to each connected clients which can only open the Socket and can wait for any incoming data. unless like a web-browser they can not perform any event and till now I have already gone through the Socket.IO and Express.IO but couldn't find anything which can be helpful to achieve what I want send raw data to open socket connections'

    Is there any other Node module to achieve this. ?

    Here is the code using WebSocketServer,

        const express = require('express');
        const http = require('http');
        const url = require('url');
        const WebSocket = require('ws');
    
        const app = express();
    
        app.use(function (req, res) {
          res.send({ msg: "hello" });
        });
    
        const server = http.createServer(app);
        const wss = new WebSocket.Server({ server });
    
       wss.on('connection', function connection(ws) {
         ws.on('message', function(message) {
           wss.broadcast(message);
         }
       }
    
       wss.broadcast = function broadcast(msg) {
         console.log(msg);
         wss.clients.forEach(function each(client) {
           client.send(msg);
         });
        };
    
        server.listen(8080, function listening() {
          console.log('Listening on %d', server.address().port);
        });
    

    Now, my query is when this code will be executed,

    wss.on('connection', function connection(ws) {
        ws.on('message', function(message) {
           wss.broadcast(message);
        }
     }