套接字io可能检测到事件发射器内存泄漏

时间:2019-04-18 08:36:07

标签: node.js socket.io

一旦事件完成,我想删除监听器以避免套接字io中出现此问题。

我收到此错误

  

MaxListenersExceededWarning:检测到可能的EventEmitter内存泄漏。添加了11个连接侦听器。使用generator.setMaxListeners()增加限制

我尝试使用removeAllListeners / removeListener / off,但是它们都不起作用。

const io = socket(httpServer); 

(async () => {
  await io.on('connection', async function (client) {

       // Some Code //

        await client.emit('message', "Done")
        io.removeAllListeners("connection")
    })
})

3 个答案:

答案 0 :(得分:0)

如果要与单个客户端进行单套接字连接,请使用await io.once代替await io.on。否则,它将对服务器端的每个请求生成多个服务器侦听器实例。

答案 1 :(得分:0)

我遇到了同样的问题,我可以使用以下代码解决问题,

mqttClient.off('message', mqttClient.listeners("message")[0]) 
  • 它将从事件中删除所需的侦听器。

mqttClient.listeners("message"):我将返回附加到“消息”事件的侦听器数组。

您也可以使用removeListner() 在这里,我使用了MQTT的情况。您也可以针对socket io遵循此过程。

答案 2 :(得分:0)

您可以使用 --trace-warnings 跟踪该警告(应该适用于 nodenodemonbabel-node)。

就我而言,在 Node 中使用 MySQL 时出现此错误:

(node:44) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit

at _addListener (events.js:247:17)

at PoolConnection.addListener (events.js:263:10)

at /app/server.js:100:1 // Redacted, but here's the specific line and column for the error 

at Ping.onOperationComplete (/app/node_modules/mysql/lib/Pool.js:110:5)

at Ping.<anonymous> (/app/node_modules/mysql/lib/Connection.js:526:10)

at Ping._callback (/app/node_modules/mysql/lib/Connection.js:488:16)

at Ping.Sequence.end (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)

at Ping.Sequence.OkPacket (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)

at Protocol._parsePacket (/app/node_modules/mysql/lib/protocol/Protocol.js:291:23)

at Parser._parsePacket (/app/node_modules/mysql/lib/protocol/Parser.js:433:10)

这就是问题所在:

const mysql_pool = mysql.createPool(mysql_pool_options);

// ...

io.on('connection',function(socket){
  socket.on('foobar', function(foo) {
    // Stuff going on ...

    // Get connection and query the database 
    mysql_pool.getConnection(function(err, current_mysql_connection) {
       current_mysql_connection.query(my_great_query, function(query_error, results) {
           // Some other stuff I do ...
       });

       // ?  Here's the issue, I didn't need to do this here ? 
       current_mysql_connection.on('error', function(err) {
           // console.log(err);
       });
    });
  });
});
相关问题