递归使用socket.pipe时的MaxListenersExceededWarning

时间:2017-12-12 14:09:56

标签: node.js sockets recursion memory-leaks

在我的Node.JS应用中,我需要通过TCP连接递归执行writer函数。这就是我的做法:

var net = require('net');
const commonConfig = require('../config.common')

var server = net.createServer(function(socket) {

    let writer  = () => {
        socket.write(Date.now() + '\n\r')
        socket.pipe(socket)
        setTimeout(writer, 1000)
    }
    writer()
});

server.listen(commonConfig.TCP_PORT, commonConfig.TCP_ADDR);

但是,我收到以下警告:

(node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 unpipe listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit (node:4497) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit

这些是由什么造成的,如何在不破坏我的功能的情况下解决这些问题?

1 个答案:

答案 0 :(得分:1)

我最近遇到类似的问题,导致最大侦听器警告。我没有使用事件监听器,但严格管道资源。当我添加太多可写管道来接收来自同一来源的数据时,例如sourcePipe.pipe(writablePipe),nodejs会发出警告。

使用 - trace-warnings 标志启动我的应用程序会提供更多详细信息,以告诉我具体发生问题的位置,这正是管道发生的代码。 node --trace-warnings app.js。将该标记传递到您的应用程序可能有助于为您提供有关您的问题的更多详细信息。

(node:5676) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMaxListeners() to increase limit
at _addListener (events.js:281:19)
at Mp4Frag.addListener (events.js:298:10)
at Mp4Frag.Readable.on (_stream_readable.js:775:35)
at Mp4Frag.Readable.pipe (_stream_readable.js:638:7)
at Socket.socket.on (L:\WebstormProjects\ffmpeg-streamer\sockets\mse.js:83:33)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at L:\WebstormProjects\ffmpeg-streamer\node_modules\socket.io\lib\socket.js:513:12
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

它指向mse.js文件的第83行,即mp4frag.pipe(writable);

我对此感到困惑,因为我知道这不是因为我有任何未处理的侦听器导致内存泄漏。我想我们有理由增加最大听众限制,因为我们已经做了尽职调查。

在我的源代码管道上,我添加了一些代码 mp4frag.setMaxListeners(20); 。现在,当我超过这个数字时,我会收到警告 MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 21 end listeners added. Use emitter.setMaxListeners() to increase limit 告诉我正在使用 20 的设定值。