error: Typeerror: wss.broadcast in not a function

error: Typeerror: wss.broadcast in not a function

我制作了一个聊天应用程序,我正在尝试广播消息,但我收到此错误:“错误:Typeerror:wss.broadcast in not a function”。

这是服务器代码:

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);

因为Class: WebSocket.Server没有广播功能,你可以阅读ws api来确认。

你可以foreach wss.clients 一条一条地发送消息进行广播。

我将代码更改为:

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

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

这也是我目前正在做的事情

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

但这也会根据我的客户数量给我返回多个响应。有谁知道如何防止这种情况?