作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想获得在我的本地机器上运行的几台服务器的连接数。
我已经成功使用 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/
我是一名优秀的程序员,十分优秀!