javascript - Calling socket.disconnect in a forEach loop doesn't actually call disconnect on all sockets -
i new javascript world. working on chat application in nodejs. have method called gracefulshutdown follows.
var gracefulshutdown = function() {     logger.info("received kill signal, shutting down gracefully.");     server.close();     logger.info('disconnecting socket.io clients');     if (object.keys(io.sockets.sockets).length == 0) process.exit();     var _map = io.sockets.sockets,         _socket;     (var _k in _map) {         if (_map.hasownproperty(_k)) {             _socket = _map[_k];             _socket.disconnect(true);         }     }     ...code here...     settimeout(function() {         logger.error("could not close connections in time, shutting down");         process.exit();     }, 10 * 1000); }   here happening in disconnect listener.the removedisconnectedclient method updates entry in db indicate removed client.
socket.on('disconnect', function() { removedisconnectedclient(socket); });
so in case disconnect event wasn't fired sockets. fired few sockets randomly array. although able fix using settimeout(fn, 0) of teammate.
i read online , understood settimeout defers execution of of code adding end of event queue. read javascript context, call stack, event loop. couldn't put of in context. don't understand why , how issue occurred. explain in detail. , best way solve or avoid them.
it hard sure without little more context rest of code in gracefulshutdown i'm surprised disconnecting of sockets @ all:
_socket = _map[ _k ]; socket.disconnect(true);   it appears assigning item _map variable _socket calling disconnect on socket, different variable. i'm guessing typo , meant call disconnect on _socket?
some of sockets might disconnecting other reasons , appearance loop disconnecting not sockets coincidence.
as far can tell code posted, socket should undefined , should getting errors trying call disconnect method on undefined.
Comments
Post a Comment