alex1997 alex1997 - 1 year ago 260
Node.js Question

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!

Answer Source

A socket can be in multiple rooms. In fact, it is automatically placed into a room with the same name as the 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, you can do this:

let rooms = Object.keys(socket.rooms).filter(function(item) {
    return item !==;

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 client does not know what rooms it is in.

One other thing to be careful of in 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download