Socket.io room with most joined - node.js

Well, title says it all. How can I get the rooms with most joined sockets? A way to list them ordered by sockets would be neat. Also if there is a way, how efficient is it? And if it isn't, can one make an own efficient way?

Not really tested, but I think this might work:
var roomNames = Object.keys(io.sockets.manager.rooms);
var sortedByNumberOfClients = roomNames.sort(function(room1, room2) {
return io.sockets.manager.rooms[room2].length - io.sockets.manager.rooms[room1].length;
});
// sortedByNumberOfClients is an array of room names, sorted on
// number of clients in the room, largest room first.
I do believe that there's a default room with an empty string ('') as name that contains all clients, so you may want to skip that. Also, I think internally socket.io adds a leading / to each room name.

Related

How can I get socket room name in socket 1.4?

I'm looking for a method or a command line to get the socket room name if possible. Any ideas or tips are highly appreciated! For example if the name of the room is 'roomName', I'm looking to get this value, ty!
A socket.io socket can be in multiple rooms. In fact, it is automatically placed into a room with the same name as the socket.id value when the socket first connects.
If what you're trying to do is get a list of all the rooms a socket is in on the server-side of the connection, you can use socket.rooms. That is an object that lists all the rooms the socket is in. If you want just an array of room names the socket is in, you can use this:
let rooms = Object.keys(socket.rooms);
If you want to eliminate the auto-generated room that matches the socket.id, you can do this:
let rooms = Object.keys(socket.rooms).filter(function(item) {
return item !== socket.id;
});
If you're trying to get this information from the client-end of things, it is not available from the client-side socket. You would have to ask the server which rooms this client is in or you'd have to have a system where the client was kept notified of what rooms it was being put in and it kept track of that data. The socket.io client does not know what rooms it is in.
One other thing to be careful of in socket.io. I've seen some asynchronous behavior in joining rooms which means that if you socket.join("someRoom") and then immediately query socket.rooms, the new room might not be there yet. If you query socket.rooms on the next tick, it will be there. I'm not sure if this always happens or just happens in some circumstances.

Node Js, websockets save connections in channels

Hi I am using websockets with node js server, the npm module is ws. I have an array where I save all my connections but now I have to separate them so I did multidimensional array something like this:
users[channel1][user_id1] = ws_user_id1_connection
The question is when I have 1 user in multiple channels:
users[channel1][user_id1] = ws_user_id1_connection
users[channel2][user_id1] = ws_user_id1_connection
users[channel3][user_id1] = ws_user_id1_connection
From preformance point of view, is this ok?. or I can accomplish this in some other way? And if I leave it like this, Is that users[channel1],users[channel2],users[channel3], they would be only reference to the ws_user_id1_connection. I mean It's not going to add the all data about ws_user_id1_connection when I create new users[channelNew], but only reference to it. The Idea is that I would like to have something as rooms/channels and in each channel to have some connected users so they can talk each other. Is that the right way? Thank you in advance.
Assuming that channel1 is a chat room, user_id1 is the userid in the room, then yes, that's a good way to implement it, you should not create a different ws per channel. You will just need to add some information to the sent data so the client knows what is the room related to the message, something like:
{
'room': 'channel1',
'from': 'otherUser_id',
'msg': 'some text message'
}
I would recommend not to use channel to refer a room because it can be confused with a ws channel. I´d also change the name of the variable ´users´ as it is not referencing users, I´d leave it like: rooms[room_id1][user_id1] = ws_user_id1_connection
Also, you may want to check Socket.io, it is a good Nodejs library designed for that kind of applications.

How to share an object across all sockets using socket.io?

I am struggling to create an object for storing the number of clients in a room. It would look something like this: { Room0: 1, Room1: 4, Room2: 3}, and whenever a socket connection/disconnection occurs (joins or leaves a room), this object will be updated and all existing sockets can have access to it at all times.
Is there a simple way to do this?
You would set a variable in the global scope (outside of the onMessage or onEvent listeners). Then, in your join rooms code, you would have a part where you would add to the count of the room. It's a crude way to do it.
var rooms = {lobby: 0, kitchen: 0}
Inside your room joining section, lets say they joined the lobby, then you would do this inside that block:
rooms.lobby++
Then, any socket that wants to know the number of people in the lobby need only call:
rooms.lobby

how to omit in sails.js two or more sockets in sails.sockets.broadcast?

I need to know how to omit in sails.js two or more sockets in sails.sockets.broadcast? I tried this:
function sendMessage(data){
var socketIds = ['socketId1','socketId2'];
sails.sockets.broadcast("room","event",data,socketIds);
//sending data to ALL sockets in the room :/
}
but it doesn't work.
I need know this because I need omit the sockets which belong to the same session. (example: session of user in computer browser and android browser)
somebody help?
There's nothing built-in that will do this for you, but broadcast is just a wrapper around emit anyway, so you can just roll your own by getting all of the socket IDs in the room you want to broadcast to, and omitting the IDs in your array.
// Get all the IDs of the sockets subscribed to "room"
var socketIds = sails.sockets.subscribers("room");
// Remove the IDs you want to omit
socketIds = _.difference(socketIds, ['socketId1','socketId2']);
// Emit your event to the rest!
sails.sockets.emit(socketIds, "event", data);

how to delete a room in socket.io

I want to statically remove all users from a room, effectively deleting that room. The idea is that another room with the same name may be created again in the future, but I want it created empty (without the listeners from the previous room).
I'm not interested in managing the room status myself but rather curious as if I can leverage socket.io internals to do this. Is this possible? (see also this question)
Is that what you want ?
io.sockets.clients(someRoom).forEach(function(s){
s.leave(someRoom);
});
For an up-to-date answer to this question, everyone who wants to remove a room can make use of Namespace.clients(cb). The cb callback will receive an error object as the first argument (null if no error) and a list of socket IDs as the second argument.
It should work fine with socket.io v2.1.0, not sure which version is the earliest compatible one.
io.of('/').in('chat').clients((error, socketIds) => {
if (error) throw error;
socketIds.forEach(socketId => io.sockets.sockets[socketId].leave('chat'));
});
#See https://github.com/socketio/socket.io/issues/3042
#See https://socket.io/docs/server-api/#namespace-clients-callback
Also, it's worth mentioning that...
Upon disconnection, sockets leave all the channels they were part of
automatically, and no special teardown is needed on your part.
https://socket.io/docs/rooms-and-namespaces/ (Disconnection)
if you are using socket io v4 or greater you can use this:
io.in("room1").socketsLeave("room1");
//all the clients in room1 will leave romm1
//hence deleting the room automatically
//as there are no more active users in it

Resources