如何以最less的延迟发送Websocket消息?

我正在编写一个在Node.js中编程的Websocket服务器,我计划发送一个多播消息给20,000个用户。 这个消息会以固定的时间间隔发送出去,但是我担心Node.js服务器的性能。

我明白,Node.jsasynchronous工作,创build和销毁线程,但我不确定它的效率。 理想情况下,我想发送消息的平均延迟5毫秒。

目前,我通过运行所有连接客户端的for循环向所有用户发送消息,如下所示:

function StartBroadcastMessage() { console.log("broadcasting socket data to client...!"); for(var i=0;i < clientsWithEvents.length;i++){ //Runs through all the clients client = clientsWithEvents[i]; if(client.eventid.toLowerCase() == serverEventName.toLowerCase()) //Checks to see if the Client Event names and server names are the same client.connection.sendUTF(GetEventSocketFeed(client.eventid)); //Sends out event data to that particular client } timeoutId = setTimeout(StartBroadcastMessage,2*1000); } 

这是发送低延迟多播消息的有效方式,还是有更好的方法?

另外,有没有一种有效的方法来在服务器上执行负载testing,模拟连接到WebSocket服务器的多个设备? (到目前为止,我已经find了这个节点的应用程序https://github.com/qarea/websockets-stress-test )

你可以使用socket.io广泛的投射信息。

 var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.broadcast.emit('user connected'); }); 

这将避免延迟(遍历所有套接字对象和格式化消息)在发送单个消息到客户端。