简体   繁体   中英

duplicates in socket.io w/ angular

Using angular and socket.io I am getting duplicate events on the client everytime the server emits. Angular is only included once, there is only one socket.io connection, and there is only one listener per event on the client. Upon receiving an event on the server, data is logged, and this process only ever happens once. Then the data is emitted and the callback is called twice on the client, despite only being in scope once(to my knowledge).

client:
//inside a controller
var thing ='foo';
socket.emit('sentUp',thing)

socket.on('sentDown',function(thing){
    console.log(thing)//this happens twice
});

server:
/*
node&express stuff here
*/
socket.on('connection',function(socket){
    socket.on('sentUp',function(stuff){
        console.log('this happened')//x1
        socket.emit('sendDown',stuff);
    });
})

Most likely your controllers are being loaded more than once. You can easily check it by logging.

Move out the socket code from the controllers and put them in a service where they're only called once.

I have found in my own socket.io client code that some of the connect events can occur each time the client reconnects. So, if the connected is lost for any reason and then the client automatically reconnects, the client may get a connect event again.

If, like me, you're adding your event handlers in the 'connect' event, then you may be accidentially adding multiple event handlers for the same event and thus you would think you were seeing duplicate data. You don't show that part of your client code so I don't know you're doing it that way, but this is an issue that hit me and it is a natural way to do things.

If that is what is happening to you, there are a couple possible work-arounds:

  1. You can add your event handlers outside the connect event. You don't have to wait for connection to finish before adding event handlers. This way, you'd only ever do them once.

  2. Before adding the event handlers you add upon connection, you can remove any previous event handlers that were installed upon connection to make sure you never get dups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM