Search code examples
javascriptnode.jswebsocketws

error: Typeerror: wss.broadcast in not a function


I made a chat app and I am trying to broadcast the message, but I am getting this error: "error: Typeerror: wss.broadcast in not a function".

this is the server code:

const WebSocket = require('ws');
let broadcast_msg;

const PORT = 5000;
const wss = new WebSocket.Server({
  port: PORT
});

wss.on("connection", (ws) =>{
  ws.on('message', function incoming(message){
    console.log('received: ', message);
    wss.broadcast(message)

  });
});

console.log("Server is liestening on port " + PORT);

Solution

  • This is what I am currently doing as well

    wss.broadcast = function broadcast(msg){
      wss.clients.forEach(function each(client){
        client.send(msg);
      });
    };
    

    But this also give me back multiple responses depending on my number of clients. Does anyone know how to prevent this?