无法读取 nodejs ws 广播/组播的“客户端”数组



尝试向所有连接广播(或在本例中为组播(价格变动。刻度在端口 4950 上传入,并在 3000 上多播出。收到以下错误;我不明白为什么无法读取clients数组:

[keith@localhost Ritchie]$ node marketDataServer.js
UDP Server listening on 192.168.1.109:4950
Websocket multicasting to 192.168.1.109:3000
Event: 'connection'
/home/keith/Documents/2017/Ritchie/marketDataServer.js:44
    ws.clients.forEach(function each(client){
              ^
TypeError: Cannot read property 'forEach' of undefined
at WebSocketServer.incoming 
(/home/keith/Documents/2017/Ritchie/marketDataServer.js:44:13)
at emitTwo (events.js:106:13)
at Socket.emit (events.js:191:7)
at UDP.onMessage (dgram.js:548:8)
  • 单播工作正常(在下面的代码中注释掉(
  • 根据下面的文档,我已将clientTracking设置为true
  • 示例
  • 基于文档中的广播示例,此处https://github.com/websockets/ws#broadcast-example


/* *************************************
Exchange Listener
Receives price ticks from the exchange
*/
var exchange_addr = '192.168.1.109';
var exchange_port = 4950;
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.bind(exchange_port, exchange_addr);
/* *************************************
Tick Data Websocket Server
Sends price ticks out to all connected websockets
*/
var websocket_addr = '192.168.1.109';
var websocket_port = 3000;
var WebSocketServer = require('ws').Server, ws = new WebSocketServer({host:websocket_addr, port:websocket_port});
console.log('Websocket Listening to ' + websocket_addr + ':' + websocket_port + ' ...');
ws.clientTracking = true;
/* *************************************
Websocket unicast
Works fine
*/    
// ws.on('connection', function(ws) {
//     console.log('New connection');
//  server.on('message', function (message, remote) {
//      var price = message + ' ';
//      ws.send(price); 
//      console.log(remote.address + ':' + remote.port +' - ' + message);
//  });
// });

/* *************************************
Broadcast/Multicast
##### NOT WORKING
*/
ws.broadcast = function broadcast(data) {
    ws.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            var price = message + ' ';
            ws.send(price); 
        }
    });
};
ws.on('connection', function(ws) {
    console.log('Event: 'connection'');
    server.on('message', function incoming(message) {
        var price = message + ' ';
        ws.clients.forEach(function each(client){
            client.send(price);
        });
        console.log(remote.address + ':' + remote.port +' - ' + message);
    });
});

您正在使用

   ws.clients.forEach(function each(client){

但是 wss 包含所有客户端,ws 只是一个客户端。所以它应该是:

wss.on('broadcast',function(msg){
  this.clients.forEach(function each(client) {
            client.send(msg);
        });
});

然后(例如(

wss.broadcast(price); 

顺便说一下,WSS 不是一个数组,而是一个集合,所以你可以拥有 wss.clients.size(而不是 .length(的客户端数量

最新更新