0
votes

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?

1
Because you are not "reconnecting". You are connecting. The reconnect event and it's associated attemptNumber only happen if the socket is attempting an automatic reconnect (because it lost it's connection from various unexpected things like the server was restarted, loss of network connectivity, etc..). When the server forcibly disconnects the socket, the socket knows exactly why it disconnected and does not try to reconnect. So socket.open() is always a connection not a re-connection. - gforce301
I have to ask. Why would you automatically reconnect when the server disconnects you? There is a reason socket.io doesn't. Most of the time you would want to handle a server forced disconnect in a different way other than just forcing another connection. Like what was the reason the server gave for disconnecting? Wouldn't you want to take different actions based on those reasons? - gforce301
The server is disconnecting the person because credentials timed out. The front end gets new credentials and reconnects to the server. - Marissa
@gforce301 If you're going to say something, I'd prefer you just come out and say it. - Marissa
"You could have gone down the path of leaving an explanation". I did explain it in my first comment. - gforce301

1 Answers

0
votes

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