gpt4 book ai didi

javascript - NodeJS 警告 : possible event emitter leak. 11 添加了开放监听器

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:34 25 4
gpt4 key购买 nike

我正在使用 NodeJS 和 WS 来测试 Websocket。为了从服务器上卸载一些工作,我想将 ping 从客户端发送到服务器,而不是相反。但是,每当我运行代码时,我都会收到此错误:

> (node) warning: possible EventEmitter memory leak detected. 11 pong listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at WebSocket.addListener (events.js:239:17)
at Object.<anonymous> (/home/ubuntu/NodeJS-Runtime/websockets/client.js:40:12)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3

这是我的代码:

for(var i=0; i<20; i++) {
const clientNum = i;
const ws = new WebSocket('ws://localhost:8080', {
perMessageDeflate: false
});

ws.onerror = function(error) {
if(!hasFailed && clientNum != 0)
console.log('failed on: ' + clientNum + error);
hasFailed = true;
}

ws.on('open', function() {
// Send keep alive messages. Close if no response.
ws.keepAlive = false;
var interval = setInterval(function() {
if (ws.keepAlive) {
ws.close();
} else {
ws.ping(null, null, true);
ws.keepAlive = true;
}
}, 25*1000); // milliseconds between pings

});
ws.on("pong", function() {
ws.keepAlive = false;
});

我在 pong 和 'on' 函数中都遇到此错误。

最佳答案

这不是错误,而是警告。如果您想禁用警告,请调用ws.setMaxListeners(0)表明您知道您正在设置超过 10 个监听器,以便运行时可以看到您知道自己在做什么。

此外,设置 ws.onerror 属性是不好的做法。相反,您需要调用 ws.on('error', function (error) {...,但这与您所询问的问题无关。

关于javascript - NodeJS 警告 : possible event emitter leak. 11 添加了开放监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061276/

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