我有一个 Node 集群 master 响应 http 请求的地方。
服务器还监听 websocket 连接(通过 socket.io )。客户端通过所述 websocket 连接到服务器。现在客户端在各种游戏之间进行选择(每个 Node 进程处理一个游戏)。
我的问题如下:
最佳答案
Is it possible to pass a socket to a node process, so that there is no need for opening a new connection?
您可以将普通 TCP 套接字发送到另一个 Node 进程,如 node.js doc here 中所述。 .基本思想是这样的:
const child = require('child_process').fork('child.js');
child.send('socket', socket);
然后,在 child.js 中,您将拥有以下内容:
process.on('message', (m, socket) => {
if (m === 'socket') {
// you have a socket here
}
});
“socket”消息标识符可以是您选择的任何消息名称 - 它并不特殊。 node.js 有代码,当你使用
child.send()
并且您发送的数据被识别为套接字,它使用特定于平台的进程间通信与其他进程共享该套接字。但是,我相信这仅适用于除 TCP 状态外尚未建立任何本地状态的普通套接字。我自己没有尝试过使用已建立的 webSocket 连接,但我认为它不起作用,因为一旦 webSocket 具有与其关联的更高级别的状态,而不仅仅是 TCP 套接字(例如加密 key ),就会出现问题,因为操作系统不会自动将该状态转移到新进程。
Should I open a new connection for each node process? How to tell the client that he should connect to the exact node process X? (Because the server might handle incoming connection-requests on its on)
这可能是获取 socket.io 连接到新进程的最简单方法。如果您确保您的新进程正在监听唯一的端口号并且它支持 CORS,那么您可以使用您在主进程和客户端之间已有的 socket.io 连接,并在其上向客户端发送一条消息这告诉客户端重新连接到哪里(什么端口号)。然后客户端可以包含代码来监听该消息并建立到该新目的地的连接。
What are the drawbacks if I just use one connection (in the master process) and pass the user messages to the respective node processes and the process messages back to the user? (I feel that it costs a lot of CPU to copy rather big objects when sending messages between the processes)
缺点正如你所猜测的。您的主进程只需要花费 CPU 能量作为双向转发数据包的中间人。这项额外的工作对您是否重要完全取决于上下文,并且必须通过测量来确定。
这是我发现的更多信息。看起来,如果在连接建立其初始 socket.io 状态之前,到达主 Node 的传入 socket.io 连接立即发送到集群子 Node ,那么这个概念也适用于 socket.io 连接。
这是an article on sending a connection to another server带有实现代码。这似乎在连接时立即完成,因此它应该适用于发往特定集群的传入 socket.io 连接。这里的想法是对特定集群进程进行粘性分配,并且在建立任何状态之前,所有到达主 Node 的任何类型的传入连接都会立即转移到集群子 Node 。
关于node.js - 使用 websockets 的 Node 集群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204408/