我想向连接到我的 sockjs-node 服务器的所有客户端广播消息。
现在我有以下代码
var clients = {};
var echo = sockjs.createServer();
echo.on('connection', function(conn) {
clients[conn.id] = conn;
for(key in clients) {
if(clients.hasOwnProperty(key)) {
clients[key].write('test');
}
}
conn.on('close', function() {
delete clients[conn.id];
});
});
有没有更有效的方法来做到这一点?
也许
var clients = [];
var echo = sockjs.createServer();
echo.on('connection', function(conn) {
var index = clients.push(conn);
var lenght = clients.length;
while(length--) {
if(clients[length] !== undefined) {
clients[length].write('test');
}
}
conn.on('close', function() {
delete clients[index];
});
});
谢谢