【问题标题】:really strange behaviour on node.js using connect-form, socket.io and express使用 connect-form、socket.io 和 express 在 node.js 上的行为真的很奇怪
【发布时间】:2011-12-16 09:11:48
【问题描述】:

以下代码:

req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    // progressEvent.download(percent);

    io.sockets.on('connection', function (socket) {        
      socket.emit('progress', { percent: percent});
      client = socket;
      });        
  });

写在一个 http post handler (express.js) 向客户端 js 发送套接字消息,但它显然创建了大量的侦听器,事实上它警告我说: “节点)警告:检测到可能的 EventEmitter 内存泄漏。添加了 11 个侦听器。使用emitter.setMaxListeners() 增加限制。”

另一方面,这段代码:

io.sockets.on('connection', function (socket) {
    progressEvent.on('progress', function(percentage) {
    console.log(percentage);
    socket.emit('progress', { percent: percentage});
    });
});

不向客户端发回任何消息,ProgressEvent 是:

var util = require('util'),
    events = require('events');

function ProgressEvent() {
    if(false === (this instanceof ProgressEvent)) {
        return new ProgressEvent();
    }

    events.EventEmitter.call(this);
}

util.inherits(ProgressEvent, events.EventEmitter);

ProgressEvent.prototype.download = function(percentage) {
    var self = this;  
    self.emit('progress', percentage);    
}

exports.ProgressEvent = ProgressEvent;

我在这个奇怪的问题上度过了愉快的一天,我真的不明白为什么 socket.io 不向客户端发送套接字消息。

整个项目在这里:https://github.com/aterreno/superuploader

感谢您的关注和帮助

【问题讨论】:

    标签: javascript node.js express socket.io


    【解决方案1】:

    您不应该在 progress 事件中监听 socket.io 连接。当用户上传文件时,您似乎正在尝试让 socket.io 进行连接,但这不会这样做。相反,它会在每次上传时触发progress 事件时侦听新连接,我猜这很常见,这就是为什么您会收到有关太多侦听器的警告。

    您想要做的是在客户端,当您初始化上传时,通过 socket.io 告诉服务器。然后服务器通过他们的会话将 socket.io 客户端与他们的上传链接起来,http://www.danielbaulig.de/socket-ioexpress/

    应该这样做

    io.sockets.on('connection', function(socket) {
      var session = socket.handshake.session;
    
      socket.on('initUpload', function() {
        session.socket = socket;
      });
    
      socket.on('disconnect', function() {
        session.socket = null;
      });
    });
    

    然后在你的路线中

    req.form.on('progress', function(bytesReceived, bytesExpected){
      var percent = (bytesReceived / bytesExpected * 100) | 0;
      if (req.session.socket) {
        socket.emit('progress', percent);
      }
    });
    

    这仅适用于每个会话一次上传,但你明白了。

    【讨论】:

    猜你喜欢
    • 2017-12-12
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多