Memory leaks using socket.io

2019-03-16 14:17发布

I've found that sockets are not fully destroyed in socket io server side when manually disconnecting them. I've found this topic on github useful. While I'm looking for some variable-links that prevent GC from cleaning sockets, I'm asking a question here.

If anyone here encountered the same problem, this would be much help.

the code that does not work:

socket.on('disconnect', function(){
    socket.removeAllListeners();
});

///...................

socket.disconnect();

Workaround that, however, uses restricted library fields:

delete io.sockets[url];
io.j = [];

1条回答
做个烂人
2楼-- · 2019-03-16 14:45

actually, this is working as intended, when you disconnect a socket you simply state you're not expecting to receive any more data from that socket right now, to actually destroy the socket you basically do the delete socket action. Use this on the disconnect event, ie:

socket.on('disconnect', function(){
    delete socket; 
})

you can also do this on the io.sockets.sockets Object on an external function:

function deleteSocket(socketID){
    delete io.sockets.sockets[socketID];
}
查看更多
登录 后发表回答