Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting socket.io users across horizontal servers

I have multiple socket.io servers scaled horizontally using a redisstore. I've got rooms setup effectively and am successfully able to broadcast to rooms across servers, etc. Now I'm trying to build a status page and what I'm failing on figuring out is how to simply count the number of users connected across all servers.

io.sockets.clients('room') and io.sockets.sockets will only tell you the number of connected clients on that one server, not all servers connected to the same RedisStore.

Suggestions?

Thanks.

like image 705
rbrc Avatar asked Aug 28 '12 17:08

rbrc


1 Answers

When a user connects to the chatroom, you can atomically increment a user counter in your RedisStore. When a user disconnects, you decrement the value. This way Redis maintains the user count and is accessible to all servers.

See INCR and DECR

SET userCount = "0"

When a user connects:

INCR userCount

When a user disconnects:

DECR userCount
like image 158
JamesOR Avatar answered Nov 13 '22 12:11

JamesOR