L
L
LemanRass092017-01-19 17:19:20
JavaScript
LemanRass09, 2017-01-19 17:19:20

Why does socket.io call connect callback multiple times after page reload?

Customer:

var token = getCookie("token");
var socket = io('http://localhost:3000/', {
    query: "&token=" + token
});

socket.on('connect', function() {
   console.log('Connected to server.');
});

Server:
io.on('connection', function (socket) {
        var token = socket.handshake.query.token;
        console.log("[Socket.IO] New user connected! Token: " + token + " Socket ID: " + socket.id);

        socket.on('disconnect', function() {
            console.log('[Socket.IO] User disconnected! Token:" + token + " Socket ID: ' + socket.id);
        });
});

When you start connect callback is called exactly 1 time as it should be.
When the page is reloaded, disconnect callback is first called, then connect callback is called 2 times with the same token and socket id.
On the next reboot, 1 disconnect and 3 connect callbacks will be called, each of which will have the same socket id.
Etc.
Everything would be fine if not for one BUT.
When sending an event from the client to the server, it arrives as many times as the number of times the connect callback has been executed. That is, if I send an event from the client after the first launch of the page, 1 event from this socket will come to the server. If I refresh the page in the browser and send the event again, it will come twice already, and then again.
In general, it is strange that inside socket.io there is no conflict about multiple sockets with the same id.
It is also strange that at least on the server side, after updating the page, connect is performed several times - on the client it is always 1.
How to deal with this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LemanRass09, 2017-01-19
@LemanRass09

I don’t know yet what it was connected with, but after a lot of different manipulations with the code, the problem was solved. Now everything seems to be returned as it was and still I don’t observe this problem anymore.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question