Theofilos Mouratidis
Theofilos Mouratidis

Reputation: 1156

Socket.io check if there are connections

I want to run a task every some seconds (2-5) then broadcast the result to the clients, the task is making an api call and then calculating somehow the returned data. Running the task without clients does not make any sense, also running the same task for every connected user makes things worse. Is using a counter and adding it up by one when connection event occurs and removing by one when disconnection occurs efficient? Is there a more clever and elegant solution?

Upvotes: 0

Views: 117

Answers (1)

vcazan
vcazan

Reputation: 137

In Socket.IO 0.7 you have a clients method on the namespaces, this returns a array of all connected sockets.

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

From there you can check the length of the array to find how many sockets are connected.

Upvotes: 1

Related Questions