NodeJS socket IO stop emitting randomly?

2019-04-18 00:16发布

I'm running Node 0.6.16 and all the modules are up to date at least according to npm (win7 x64). I could notice that, even if I have no disconnection occurring, but for some reason, after a while, I couldn't tell, maybe 1 hour, the browser doesn't receive any data. It appears to be more frequent on FF than on Chrome.

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

This never fires for that particular event (I mean it could happen but then I get the log and socket.io auto reconnects - In this case, nothing happens, it just stops working and this is the most frequent event).

So I don't know where to look. NodeJS still logs an heartbeat but for some reason, the connection is not going through. I am suspecting that, on tab change of (any?) browser, after a while, as the window / tab doesn't have focus anymore, socket.io stops receiving data ? I could be wrong and it could be not related to the focus, but this is my primary lead. Anyone else got any ideas?

Edit: client side is pretty straight forward :

socket = io.connect('http://xxx.xxx.xxx.xxx:8081', {secure:false, 'reconnect': true, 'reconnection delay': 500, 'max reconnection attempts': 10});      
            socket.on('connect', function(){console.log('connected')});
            socket.on('message', function(data){//do something);        

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

Edit2 : After updating to latest version of socket.io (1.2.1) and node v0.10.35 I still have the same issue. Even more surprising, I added the following piece of code in the client:

function checkSocket(){
    if(socket){
        if(!socket.connected){
            console.log('socket disconnected');
            clearInterval(intv);
        }
    }       
}

intv = setInterval(checkSocket, 1000);

While the function runs every second, it never logs that the socket is disconnected, even if it does not receive anything anymore and still being sent heartbeats..

Edit3: Ok it was on my server side code, some socket were being destroyed. Also updated to v1.x and forced reconnection.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-18 00:36

So since it seems I have no more issue, I thought I would share my back-end code. My issue I believe was that I was overwriting the socket.

var clients = {};
var app = require('https').createServer(options),
io = require('socket.io').listen(app);  
app.listen(8081);

io.sockets.on('connection', function(__socket) {
    var id = __socket.id;
    var ip = __socket.request.connection.remoteAddress;
    clients[id] = {socket:__socket, ip:ip}; 
    clients[id].socket.on('disconnect', function() {
        delete clients[id];     
   });
});
查看更多
登录 后发表回答