我正在使用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 - Node 警告:可能的事件发射器泄漏。添加了11个开放的监听器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44061276/