I have been working on an online game in node and Socket.io (with basically all of the game's state being in Socket.io), but one thing has been bugging me. Right now, a user has to close the page to disconnect from the server. Obviously this needs to be much more elegant, and I need a proper "Logout" button.
But for the life of me I can't figure out how to make one. I searched on Google for an answer, and I have combed through SO. I went digging through the Socket object in Socket.io, and I have tried these 3 related-sounding methods of flipping something on the Socket object to disconnect that user:
socket.disconnected = true;
//and
socket.manager.connected[socket.id] = false;
//and
socket.manager.open[socket.id] = false;
But none of these change the fact that the user is still connected. How is this done?
On client side you might subscribe to event of disconnection:
socket.on('disconnect', function() {
console.log('disconnected');
});
Same on server side in order to make sure your logic is aware of such behaviour. Then in order to allow user manually disconnect you can actually close connection directly:
socket.disconnect();
Or if some extra interaction with server needed you can emit message to server 'disconnect me', then server will perform own stuff, optionally can emit response to client and call socket.disconnect();