Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.IO: Reconnect Causes Server Connect Code to Run Twice

Whenever I disconnect using socket.disconnect(); and then reconnect using socket.connect();, the server runs my handshake code twice. The strange thing is, even though the server connection code runs twice, there is only one connection in my array after reconnecting. This happens on an accidental disconnection, intentional, or even if the server restarts. Bit of code:

io.on('connection', OnConnect);
function OnConnect(socket) {

    var connection = { socket: socket, realIp: ip, token: GenerateConnToken() };
    connections.push(connection);
    console.log('Connected');

    // Client will respond to this by emitting "client-send-info".
    // This is emitted once on initial connect, but twice on reconnect.
    socket.emit('acknowledge', connection.token);

    socket.on('client-send-info', function() {

        console.log('Client Sent Info');
    });

    socket.on('disconnect', function() {
        console.log('Disconnected');
    });
}

The above code, when a client connects, disconnects, and then reconnects once, will produce the following log:

Connected

Client Sent Info

Disconnected

Connected

Client Sent Info

Client Sent Info

Why is it that, when reconnecting, the connection code will run twice, but only create one connection object?

EDIT: Upon further inspection, it seems that a different piece of my connection code is being performed twice when the client reconnects. The above code is updated to reflect the relevant information.

like image 453
Nifty255 Avatar asked Oct 31 '22 09:10

Nifty255


1 Answers

Strangely, the solution is completely client side. Instead of the following code:

var socket = io.connect();
socket.on('connect' function() {
    socket.on('acknowledge', function() {

    });
});

You have to use:

var socket = io.connect();
socket.on('connect' function() {

});

socket.on('acknowledge', function() {

});

Otherwise, the server will appear to be sending multiple emits when it is in reality only sending one, and it's the client that falsely receives multiples. With the second code format, the client successfully connects initially, disconnects, and reconnects without receiving multiple emits.

Simply, don't put any additional socket.on('x') calls inside the on('connection') call. Leave them all outside it.

like image 118
Nifty255 Avatar answered Nov 09 '22 15:11

Nifty255