The socket variable in io.sockets.on('connection', function(socket) {...}) is different for each connection.
Since your global.socket code always has a link to a socket relative to the last connected client, it is normal if this client disconnects, this socket will die.
In any case, I see no reason to use a global variable. If you need to send a message to a specific client, you can use the socket variable in the connection callback:
io.sockets.on('connection', function (socket) { socket.emit('foo', 'bar'); }
If you need to access sockets in another module, you can export the sessionsConnections object and access the socket that you need by its identifier:
//In app.js exports.connections = sessionsConnections; //In match.js var app = require('./app.js'); app.connections[clientId].emit('foo', 'bar');
Of course you need to track the id somewhere.
source share