来自socket.io处理程序中的函数的EventEmitter内存泄漏

时间:2014-01-28 15:30:51

标签: javascript node.js socket.io

我的服务器需要一个动态值,该值会从生成的进程中不断更新。我试图在服务器范围之外创建一个自定义侦听器,因为我收到了潜在的内存泄漏错误,但是在服务器上发生多次连接/断开连接后,我仍然收到这些消息。为什么在断开连接事件监听器期间删除初始连接后添加的侦听器?

var express = require('express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');

var app     = express(),
    server  = http.createServer(app),
    io      = require('socket.io').listen(server);

function Looper(req)  {
    this.req = req;
    EventEmitter.call(this);
}
sys.inherits(Looper, EventEmitter);

Looper.prototype.run = function() {
    var self = this;
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        self.emit('output',data);
    });
}

Looper.prototype.output = function(callback) {
    this.on('output', function(data) {
        return callback(data.trim());
    });
}

var looper = new Looper('blah');
looper.run();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.send(
        "<script src='/socket.io/socket.io.js'></script>\n"+
        "<script>\n"+
        "\tvar socket=io.connect('http://127.0.0.1:3000');\n"+
        "\tsocket.on('stream', function(data) {\n"+
        "\t\tconsole.log(data);\n"+
        "\t});\n"+
        "</script>\n"
    );
});
server.listen(3000);

io.sockets.on('connection', function(webSocket) {
    looper.output(function(res) {
        webSocket.emit('stream',res);
    });

    webSocket.on('disconnect', function() {
        looper.removeListener('output',looper.output); // <- not remove listener added when connection was made
    });
});

1 个答案:

答案 0 :(得分:0)

每次调用looper.output到事件'output'时,都会添加(!)一个额外的回调函数。我不知道你想要实现什么,但是只使用this.once('output', ...)或者将回调设置移动到对象或首先删除旧函数来获得此调用...