7

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"

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • check this link http://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients – Dinesh Jan 19 '17 at 12:29

2 Answers2

4

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;
}
mk12ok
  • 1,293
  • 14
  • 14
3

Maybe you need this: io.sockets.connected

var clients = Object.keys(io.sockets.connected);

then if you need a socket:
var socket = io.sockets.connected[socket_id]

onehalf
  • 2,602
  • 1
  • 15
  • 15