Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internal socket.io clients list location

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"

like image 555
Alexander Mills Avatar asked Jan 19 '17 08:01

Alexander Mills


1 Answers

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;
}
like image 145
mk12ok Avatar answered Sep 28 '22 08:09

mk12ok