3
votes
  • On server the disconnect event is triggered after connect when the network had dropped and the client reconnects.

Client code:

var url ='192.168.1.101', port = '80',
    socket = io.connect('http://' + url + ':' + port, {
    'reconnect': true,
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    timeout: 1000
});

//reconnect event

socket.on('reconnect', function (nr) {
    console.log('reconnected, nr: ', nr);
});

//connect event

socket.on('connect', function () {
    console.log('connected');
});

//disconnect event

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

Server code:

'use strict';
var fs = require('fs'),
    express = require('express'),
    app = express(),
    io = require('socket.io'),
    server = require('http').createServer(app),
    compress = require('compression'),
    socket;

app.use(compress({level: 9}));

server.listen(port, url);
socket = io.listen(server, {'pingTimeout': 1000, 'pingInterval': 3000});

socket.on('connection', function (client) {
    console.log('client connected');

    client.on('disconnect', function () {
        console.log('client disconnected');
    });
});
        
- Result on server if client reconnects:

> client connected
> client disconnected

Can someone explain to me why this is happening?
2
Does it attempt to reconnect? or does it just disconnect and thats it? - Deckerz

2 Answers

0
votes

The client and server exchange heart beat messages while the connection is active. When the server stops receiving these messages it will declare the client disconnected. The client can also disconnect explicitly.

What you are experiencing though is probably the first case. The client has a retry logic so whenever the connection is dropped it'll try to reconnect. I'm not sure why this is happen, you may want to look at the network tab in your browser's console to see what's happening at the request/response level.

REF: https://github.com/socketio/socket.io/issues/1910

https://github.com/miguelgrinberg/Flask-SocketIO/issues/116

0
votes

Are you sure that the client disconnected and client connected texts are from the same socket/connection? Maybe first one is from previous connection and it is just delivered to you a bit later than info about new connection?

Try to generate and add some ID numbers to connections/sockets and output them to console along with info messages.