Socket IO reconnect?

前端 未结 5 1641
终归单人心
终归单人心 2020-12-12 19:06

How to reconnect to socket io once disconnect has been called?

Here\'s the code

function initSocket(__bool){                    
    if(         


        
5条回答
  •  伪装坚强ぢ
    2020-12-12 20:11

    I know you already have an answer, but I arrived here because the socket.IO client reconnection feature is broken in node at the moment.

    Active bugs on the github repo show that lots of people aren't getting events on connect failure, and reconnect isn't happening automatically.

    To work around this, you can create a manual reconnect loop as follows:

    var socketClient = socketioClient.connect(socketHost)
    
    var tryReconnect = function(){
    
        if (socketClient.socket.connected === false &&
            socketClient.socket.connecting === false) {
            // use a connect() or reconnect() here if you want
            socketClient.socket.connect()
       }
    }
    
    var intervalID = setInterval(tryReconnect, 2000)
    
    socketClient.on('connect', function () {
        // once client connects, clear the reconnection interval function
        clearInterval(intervalID)
        //... do other stuff
    })
    

提交回复
热议问题