【问题标题】:Socket.io changefeed multiple emits on refresh / reload刷新/重新加载时 Socket.io changefeed 多次发出
【发布时间】:2018-06-16 15:51:11
【问题描述】:

我遇到了这个确切的问题: https://github.com/rethinkdb/rethinkdb/issues/6503

我第一次连接时,它 console.logs 1 次。 如果我刷新它 console.log 2 次。 如果我再次刷新,它将控制台记录 3 次。依此类推。每次重新加载时,请继续添加一个 console.log / run。与 socket.emit 相同。它会在每次重新加载时不断增加 1 个额外的值。

在上面的链接中,他使用以下代码描述了如何修复它:

options.socket.on('close', () => {
  conn.close({ noreplyWait: false });
});

我很想测试这个,但不知道怎么做?任何人都可以帮助我朝着正确的方向前进吗?

我的服务器代码如下所示:

io.on('connection', function(socket){
        console.log('a user connected: ' + socket.id);
        r.table('Groups')
            .filter(r.row("members")
            .contains(req.user['id']))
            .changes({ includeInitial: true })
            .run()
            .then(function(feed){
                 feed.each(function(err, item){
                  console.log(req.user['entra']);
                //console.log(JSON.stringify(item, null, 2));

                socket.emit('group',item.new_val);
             })
          })
   });

客户端代码:

var url = 'http://'+top.location.hostname+':4200';
var socket = io.connect(url);

socket.on('group', function(msg){
  console.log(msg);
  if (msg != null) {
    $('span#groupName').html(msg['groupName']);
  }else{
    $('span#groupName').html('Not member of any group yet');
  }

});

我还找到了这样修复它的人:https://gist.github.com/jamilservicos/e7c09e3701a7ba5ff817096ef8426d94

它只是为一件我认为不应该成为问题的小事编写了很多代码。我在上面的代码中做错了什么吗?

知道如何解决问题或如何从第一个链接测试解决方案吗?

【问题讨论】:

    标签: javascript node.js express socket.io rethinkdb


    【解决方案1】:

    我终于解决了!

    我补充说:

    io.removeAllListeners();
    

    就在下面:

    io.on('connection', function(socket){
    

    所以现在看起来像这样:

    io.on('connection', function(socket){
            io.removeAllListeners();
            console.log('a user connected: ' + socket.id);
            r.table('Groups')
                .filter(r.row("members")
                .contains(req.user['id']))
                .changes({ includeInitial: true })
                .run()
                .then(function(feed){
                     feed.each(function(err, item){
                      console.log(req.user['entra']);
                    //console.log(JSON.stringify(item, null, 2));
    
                    socket.emit('group',item.new_val);
                 })
              })
       });
    

    它有效,我不再收到多条消息/console.logs 或发出。

    【讨论】:

    • 这拯救了我的灵魂。
    猜你喜欢
    • 2013-12-27
    • 2015-08-10
    • 2020-06-17
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多