How can I disconnect/close all sockets on server side ?
Maybe restarting the socket.io module from the server side ?
(using the lateste socket.io)
close([callback]) Closes the socket.io server. The callback argument is optional and will be called when all connections are closed.
As we saw in the performance section of this article, a Socket.IO server can sustain 10,000 concurrent connections.
Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.
You can check the socket. connected property: var socket = io. connect(); console.
Unfortunately, socket.io does not have a publicly documented interface that has been the same from one version to the next to do such a basic function as iterate all connected sockets. If you want to follow the entire history of various ways to do this, then you can follow the whole version history in this question: Socket.IO - how do I get a list of connected sockets/clients?, but you have to pay attention only to answers that apply to specific socket.io versions you are using and then test them for your specific version.
As of Aug 2018, attempting to use only documented interfaces in socket.io, one could use either of these to get a list of connected sockets and then just iterate over them to disconnect them as shown above:
function getConnectedSockets() {
return Object.values(io.of("/").connected);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
Depending upon the client configuration, the clients may try to reconnect.
You could also just maintain your own connect socket list:
const connectedSockets = new Set();
io.on('connection', s => {
connectedSockets.add(s);
s.on('disconnect', () => {
connectedSockets.delete(s);
});
});
function getConnectedSockets() {
return Array.from(connectedSockets);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
If you are using an older version of socket.io (particularly before v1.4), you will have to either test this to make sure it works in your older version or follow the version history in the above mentioned reference and find an answer there that targets your specific version of socket.io.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With