Socket.io changefeed multiple emits on refresh / r

2019-08-25 03:50发布

问题:

I'm having this exact problem: https://github.com/rethinkdb/rethinkdb/issues/6503

First time I connect, it console.logs 1 time. If I refresh it console.log 2 times. If I refresh again, it console logs 3 times. and so on.Keep adding one more console.log / run to each reload. The same with socket.emit. It keeps adding 1 extra on each reload.

In the link above he describes how to fix it, with this code:

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

I would love to test this, but have no idea how to? Can anyone help me in the right direction?

My server code looks like this:

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);
             })
          })
   });

And Client code:

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');
  }

});

I also found someone who fixes it this way: https://gist.github.com/jamilservicos/e7c09e3701a7ba5ff817096ef8426d94

It just seams like a lot of code for a small thing I wouldn't think should be a problem. Am I doing anything wrong in my code above?

Any idea how to fix the issue or how I can test the solution from the first link?

回答1:

I finally solved it!

I added:

io.removeAllListeners();

Right below:

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

So now it looks like this:

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);
             })
          })
   });

And it works and I don't get multiple messages / console.logs or emits anymore.