getting how many people are in a chat room in socket.io
If you're using version < 1,
var clients = io.sockets.clients(nick.room); // all users from room
How to check how many participants are connected to my chat room using socket IO
In the latest version of socket.io, you can see how many sockets are in a given chat room with this:
io.sockets.adapter.rooms["testRoom"].length
Where testRoom
is whatever the name of your chat room is (whatever you used .join()
with.
io.sockets.adapter.rooms["testRoom"]
is an Object where each property name except .length
is the socket.id of the socket that is in the chat room.
FYI, the code you show in your question doesn't appear to have anything to do with socket.io chat rooms so that has me a bit perplexed.
How to find amount of clients in room in socketio
I found the answer, io.sockets.adapter.rooms
is a map of sets which means to get the size of a specific room is io.sockets.adapter.rooms.get(code).size
. What I had tried to do seems to be what works for earlier versions but not >3.
How do I get a list of connected sockets/clients with Socket.IO?
In Socket.IO 0.7 you have a clients
method on the namespaces. This returns an array of all connected sockets.
API for no namespace:
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
For a namespace
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
Note: This solution only works with a version prior to 1.0
From 1.x and above, please refer to getting how many people are in a chat room in socket.io.
Socket.IO Connected User Count
There is a github issue for this. The problem is that whenever someone disconnects socket.io doesn't delete ( splice ) from the array, but simply sets the value to "null", so in fact you have a lot of null values in your array, which make your clients().length bigger than the connections you have in reality.
You have to manage a different way for counting your clients, e.g. something like
socket.on('connect', function() { connectCounter++; });
socket.on('disconnect', function() { connectCounter--; });
It's a mind buzz, why the people behind socket.io have left the things like that, but it is better explain in the github issue, which I posted as a link!
Socket IO Rooms: Get list of clients in specific room
Just a few things.
when you have the
socket
you can then set the properties like:socket.nickname = 'Earl';
later to use the save property for example in a console log:console.log(socket.nickname);
you where missing a closing quote (') in your:
console.log('User joined chat room 1);
Im not entirely sure about your loop.
Below is the amended code should help you out a bit, also be aware the loop i am using below is asynchronous and this may effect how you handle data transfers.
socket.nickname = 'Earl';
socket.join('chatroom1');
console.log('User joined chat room 1');
var roster = io.sockets.clients('chatroom1');
roster.forEach(function(client) {
console.log('Username: ' + client.nickname);
});
to help you out more i would need to see all your code as this does not give me context.
socket io rooms names and number of users inside specific room
Indeed, a socket.io room only exists as long as there is one client connected to it. Additionally, it is destroyed to free up memory once the last client leaves it as shown here in the socket adapter:
if (this.rooms[room].length === 0) delete this.rooms[room];
To get the real room names, you will have to keep track of them on the server side. The easiest way would be an object of user counts indexed by rooms names.
const usersByRooms = {}
You would first send this full object when a new socket connects
socket.emit('getAllRooms' usersByRoom)
And iterate on this object by its keys when you receive it on the client
socket.on('getAllRooms', (usersByRoom) => {
Object.keys(usersByRoom).forEach(roomName =>
console.log(roomName, usersByRoom[roomName]))
})
I'm assuming your page would need to have the number of clients connected to your room updated live. For this, you need to have a method to broadcast the number of users of a room if it were to change, and updating your usersByRooms
cache accordingly, like this:
const updateCount = roomName => {
const userCount = io.sockets.clients(roomName).length
// we do not update if the count did not change
if (userCount === usersByRoom[roomName]) { return }
usersByRoom[roomName] = userCount
io.emit('updateCount', { roomName, userCount })
}
This method needs to be called every-time a socket joins and leaves a room successfully by using the callback of these two methods:
socket.join(roomName, () => {
updateCount(roomName)
})
socket.leave(roomName, () => {
updateCount(roomName)
})
You could now hook into the new disconnecting
event added in socket.io#2332 in case your client disconnects or simply closes your application to broadcast the new count to any room the socket was connected to.
socket.on('disconnecting', () => {
const rooms = socket.rooms.slice()
// ...
})
This approach might be a little tricky as you would need to keep track of the rooms of the socket being disconnected and update them right after the socket completed the disconnection.
A simpler method would be to iterate over all the rooms right after every socket disconnection and call the updateCount
, since the method only broadcasts an event if the user count of the room changed, it should be fine un less you have thousands of rooms.
socket.on('disconnected', () => {
Object.keys(usersByRooms).forEach(updateCount)
})
Please note that it gets a bit tricky if you are using a socket cluster, but I'm assuming a normal setup.
socket.io 2.0 get connected clients in a room
Unfortunately, this answer doesn't completely satisfy OPs question. If you are using socket.io-redis
to manage socket connections you can get connected clients like
io.of('/').adapter.clients((err, clients) => {
console.log(clients); // an array containing all connected socket ids
});
io.of('/').adapter.clients(['room1', 'room2'], (err, clients) => {
console.log(clients); // an array containing socket ids in 'room1' and/or 'room2'
});
// you can also use
io.in('room3').clients((err, clients) => {
console.log(clients); // an array containing socket ids in 'room3'
});
this is from : https://github.com/socketio/socket.io-redis#redisadapterclientsroomsarray-fnfunction
Related Topics
Orderby Multiple Fields in Angular
JavaScript Getelementbyid Based on a Partial String
Typescript: Deep Keyof of a Nested Object, with Related Type
Passing Python Data to JavaScript via Django
Put JavaScript in One .Js File or Break It Out into Multiple .Js Files
How to Get the Index of an Array in a Meteor Template Each Loop
Batchsize Field Name Ignored in Field Projection
How Not to Forget Using Await Everywhere in JavaScript
Angular App Has to Clear Cache After New Deployment
Can't Access Cookies from Document.Cookie in Js, But Browser Shows Cookies Exist
Reactjs: Prevent Multiple Times Button Press
Get Character Value from Keycode in JavaScript... Then Trim
How to Populate the Options of a Select Element in JavaScript
Jquery Clone Form Fields and Increment Id
Create an Empty Object in JavaScript with {} or New Object()