gpt4 book ai didi

node.js - 如何在 Node.js 中获取现有服务器的实例?

转载 作者:行者123 更新时间:2023-12-03 11:49:48 42 4
gpt4 key购买 nike

我想获得在我的本地机器上运行的几台服务器的连接数。

我已经成功使用 server.getConnections() 在通过 net.createServer() 创建的服务器上,但是我不知道如何在已经启动的服务器上使用它。

我尝试通过连接获取服务器实例,使用 net.connect() .连接创建成功,我得到一个新的 net.Socket 对象,但我的理解是我实际上需要一个 net.Server 为了使用getConnections() .

所以我的问题是,我如何获得 net.Server已经运行的服务器的实例?

最佳答案

我意识到我的问题是一个 XY 问题,所以向所有试图回答它的人道歉。

我怀疑字面问题“我如何获得现有服务器的实例”的答案是:“你不能”。

我应该在问题中添加更多细节,尤其是我想要实现的目标。

我的应用程序是负载平衡器/反向代理服务器。最初我能够使用 getConnections()因为我会从同一个脚本启动代理服务器和一些虚拟服务器。然而,我想让虚拟服务器和代理彼此分开,所以即使我确实可以完全控制它们,我也需要假装我实际上并不拥有这些服务器。

最后,我针对我的具体情况找到的解决方案是保留我可以连接的服务器的哈希列表(通过反向代理),并在每次连接到特定服务器时增加连接计数器:

let servers = [
{ port: 4000, connectionsCounter: 0 },
{ port: 5000, connectionsCounter: 0 },
{ port: 6000, connectionsCounter: 0 },
];

let myProxyServer = net.createServer((socket) => {
// Open a connection to the first server in the list
net.connect(servers[0].port, () => {

// Once connected, increment the connections counter
socket.on('connect', () => {
servers[0].connectionsCounter++;
});

// When the connection ends, decrement the counter
socket.on('close', () => {
servers[0].connectionsCounter--;
});
});
});

我希望这会对某人有所帮助。

关于node.js - 如何在 Node.js 中获取现有服务器的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61291241/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com