I am wondering if Socket.io will internally do bookkeeping and allow the user to retrieve a list of clients, or if we will manually need to keep track of a list of connected clients like so:
var Server = require('socket.io');
var io = new Server(3980, {});
const clients = [];
io.on('connection', function (socket) {
clients.push(socket);
socket.on('disconnect', function () {
clients.splice(clients.indexOf(socket),1);
});
});
does socket.io store a list of connections, somewhere like:
io.connections
or
io.sockets
having more trouble than I expected to find this information, for newer versions of socket.io. I am using version => "socket.io": "^1.7.2"
The following function will give you an array of socket objects:
function clients(namespace) {
var res = [];
var ns = io.of(namespace || "/");
if (ns) {
Object.keys(ns.connected).forEach(function (id) {
res.push(ns.connected[id]);
});
}
return res;
}
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