Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disconnect all sockets serve side using socket.io?

Tags:

socket.io

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)

like image 398
yarek Avatar asked Jun 01 '15 10:06

yarek


People also ask

How do I turn off Socket.IO on my server?

close([callback])​ Closes the socket.io server. The callback argument is optional and will be called when all connections are closed.

How many Socket connections can Socket.IO handle?

As we saw in the performance section of this article, a Socket.IO server can sustain 10,000 concurrent connections.

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.


1 Answers

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.

like image 106
jfriend00 Avatar answered Oct 19 '22 07:10

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!