尝试向所有连接广播(或在此情况下,多播)价格标记。 Ticks进入端口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
/* *************************************
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);
});
});
答案 0 :(得分:0)
您正在使用
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)的客户端