我正在使用带有粘性会话的socket.io(https://github.com/indutny/sticky-session)。我有一个小聊天应用程序,并且当我在一台机器上使用2个或更多套接字时,socket.on(...)
事件监听器的触发速度非常慢。当我为每个集群仅使用一个套接字连接时,一切都运行得很好而且速度很快。可能是什么原因。可能是因为粘性会话?
修改
这是套接字函数(我的工作者 - 集群):
WebSockets.on('connect', function (socket) {
console.log(`${process.pid}`);
//send data example: socket.emit('news', {a: "b"});
//TODO: implement switch case that validates which chat type it is.
//TODO: why is the event so slow when using 2 connections?: https://socketio.slack.com/messages/C02AS4S1H/
socket.on('chat message', function (msg) {
console.log("sending message: " + msg)
try {
//send the message to all other cluster-workers:
process.send({ chat_message: msg });
} catch (e) { }
});
//if the cluster gets a message then he sends it to the user, if its the correct user
function message_handler(msg) {
try {
//TODO: send message only to the correct users
if (msg != null && msg.chat_message != null) {
WebSockets.emit('chat message', msg.chat_message);
}
} catch (e) { }
}
process.on('message', message_handler);
//When the socket disconnects:
socket.on('disconnect', function(reason) {
//remove the event listener:
process.removeListener('message', message_handler);
});
});
说明:我将从套接字获得的所有数据发送到所有其他集群。然后我抓住他们:
process.on('message', message_handler);
发送聊天消息。
中创建了具有粘性会话的群集