Created
September 27, 2016 07:39
-
-
Save stewartcelani/c64fb5cc9765ca2c698939a4b3bbbf51 to your computer and use it in GitHub Desktop.
From https://stackoverflow.com/questions/33078182/socket-io-number-of-users-in-a-room Perhaps a way to get presence indicators.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Get the room: | |
var room = io.sockets.adapter.rooms[roomId] || {}; | |
//Declaration of number of users variable | |
var numUsers; | |
//If there are any user connected in the room, create the object | |
if(room.user===undefined) | |
room.user = {}; | |
//If you join the room and have another opened session, increase the number of sessions | |
if(room.user[socket.request.user.id] && isConnect) | |
room.user[socket.request.user.id] += 1; | |
//If you leave the room and have another opened session, decrease the number of sessions | |
else if(room.user[socket.request.user.id] && !isConnect){ | |
room.user[socket.request.user.id] -= 1; | |
//If the number of sessions is 0, delete the user from the object | |
if(room.user[socket.request.user.id]===0) | |
delete room.user[socket.request.user.id]; | |
} | |
//If the user don't have any session and join the room, put 1 session in the object | |
else if(isConnect){ | |
room.user[socket.request.user.id] = 1; | |
} | |
//Get the number of users from room.user object | |
numUsers = Object.keys(room.user).length; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment