简体   繁体   中英

Why does the reconnect function not trigger on manual reconnect Socket.IO

When the node server disconnects the client using socket.disconnect(true); I manually open the connection again on the client side using socket.open() .

The problem is that when the socket.open() is triggered, the socket.on('reconnect', (attemptNumber) => { function isn't. socket.on('connect', () => { works fine, but I'd like the code inside to only execute on a reconnect after the server has closed on the connection. Why doesn't the reconnect function work on a manual reconnect and is there something I can do to fix or work around this problem?

You could handle it just like in this very simple implementation:

class SocketService {
    .
    .
    .
    static registerSocket(opts) {
        socket.on('open', () => { 
            console.log('socket connected')
            socket.onclose = (e) => {
                console.log('Socket is closed. Reconnect will be attempted in 1.5 second.', e.reason); 
                setTimeout(() =>
                    /* 
                    * Try connect again after 1.5s, 
                    * could be improved with a while 
                    * and a number max of retries
                    */
                    SocketService
                        .registerSocket(opts)
                ,1500); 
            };
        });
        socket.onerror = () => {
            // Handle first connection error here
        };
    }
}

Implementing this way, you have some insurances.

The first one is that you ensure that you're handling the reconnection logic and the second is the you're handling the connection error as well

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