Monday, January 30, 2017

Internal socket.io clients list location

Leave a Comment

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"

2 Answers

Answers 1

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; } 

Answers 2

Maybe you need this: io.sockets.connected

var clients = Object.keys(io.sockets.connected); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment