How to send broadcast to all connected client in node js

Viewed 19324

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);
    }
 }
2 Answers

Try the following code to broadcast message from server to every client.

wss.clients.forEach(function(client) {
    client.send(data.toString());
});

Demo server code,

const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 2055 },()=>{
    console.log('server started')
})
wss.on('connection', (ws) => {
   ws.on('message', (data) => {
      console.log('data received \n '+ data)
      wss.clients.forEach(function(client) {
         client.send(data.toString());
      });
   })
})
wss.on('listening',()=>{
   console.log('listening on 2055')
})
Related