Ismar Slomic
Ismar Slomic

Reputation: 5514

Joining same room more then once and clients in a room

I'm trying to figure out what happens if the clients emits to join the same room more then once, To test and find answer on this I wanted initially to find out how many clients room has after same clients send more then one emit for joining the room, but Rooms chapter in wiki https://github.com/Automattic/socket.io/wiki/Rooms is outdated. When I try to use "io.sockets.clients('room')" I get error "Object # has no method 'clients'".

So I got two questions: 1. what happens if client tries to join same room more then once? Will he get emits for that room for each time he has tried to join? 2. How can I find out which clients are in a room?

Im using socket.io v1.0.2

Upvotes: 11

Views: 7251

Answers (3)

Junaid Yousaf Lodhi
Junaid Yousaf Lodhi

Reputation: 29

Its working fine and does not gives any error,it ignores the second request for joining the room from that socket which is already in the room.

I have actually tried and implemented a solution where when user click on message notification it joins that specific room from which the notification came and, and when he sends very first message he again join that specific room (It is because I have build a Chat-Directive in AngularJS).

Client Side

1) User Open Notification

Socket.emit('JoinRoomWithThsID', notification.ConversationID);

2) user Sends First Message in that room

Socket.emit('patientChatRoomMessage', adminmessage);

Upvotes: 0

Tola
Tola

Reputation: 631

Fixed getting clients in a room at socket.io ~1.4.5 like this:

    socket.join('test room');
    var room = io.sockets.adapter.rooms['test room'];
    console.log(room);
    for (var socketId in room.sockets) {
      console.log(io.sockets.connected[socketId]);
    }

Upvotes: 0

Ismar Slomic
Ismar Slomic

Reputation: 5514

I got an answer on this question at socket.io github.

  1. As per this line of code, the socket will receive emits only once. The socket is added to a room only once, and if another attempt is made for the same socket to join the room, this attempt will be ignored.

  2. There is currently no public API for getting the clients, and there is some discussion ongoing in #1428. If you really need to get them, for some reason, you can fetch the actual clients from the adapter, assuming you are not using the redis adapter like so:

    socket.join('test room');
    var clients = io.sockets.adapter.rooms['test room'];
    console.log(clients);
    for (var clientId in clients) {
      console.log(io.sockets.connected[clientId]);
    }
    

Upvotes: 19

Related Questions