socket.io creates one more connection after reconnecting

前端 未结 2 1837
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 23:55

I am trying a simple chat application here with socket.io and node.js. Every time I restart the node.js server, socket.io automatically reconnects and somehow creates one mo

相关标签:
2条回答
  • 2020-12-09 00:39

    By default on disconnect socket.io reconnects the lost connection, which re runs the connect event. So everytime it reconnects you add one more event listener for recieving messages. So you get multiple number of messages equal to server restarts/connection loss.

    Incoming Chat: 
    Connected
    dsdadsada
    Disconnected                         //recieved by 1st listener
    Connected                            //added 2nd listener
    adasd
    Disconnected                         //recieved by 1st listener
    Disconnected                         //recieved by 2nd listener
    Connected                            //added 3rd listener
    

    You should listen to the first connect using once instead of on, which runs eventhandler the first time only. Try

    iosocket.once('connect', function () {
    

    instead of

    iosocket.on('connect', function () {
    
    0 讨论(0)
  • 2020-12-09 00:42

    Try to write the index.html in this way instead:

     iosocket.on('connect', function () {
          $('#incomingChatMessages').append($('<li>Connected</li>'));
     });
    
     iosocket.on('message', function(message) {
          $('#incomingChatMessages').append($('<li></li>').text(message));
     });
    
     iosocket.on('disconnect', function() {
          $('#incomingChatMessages').append('<li>Disconnected</li>');
     });
    

    It may be caused by the other 2 eventlisteners was registered to the connect event. When the client disconnected, the other 2 listeners will still here and doesn't get unregistered.

    0 讨论(0)
提交回复
热议问题