Socket IO Rooms: Get list of clients in specific r

2019-03-15 00:30发布

I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

socket.set('nickname', "Earl");  
socket.join('chatroom1');
console.log('User joined chat room 1);

var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);   
}

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.

7条回答
唯我独甜
2楼-- · 2019-03-15 01:32

For Socket.io greater than v1.0 and node v6.0+ use the following code:

function getSockets(room) { // will return all sockets with room name
  return Object.entries(io.sockets.adapter.rooms[room] === undefined ?
  {} : io.sockets.adapter.rooms[room].sockets )
    .filter(([id, status]) => status) // get only status = true sockets 
    .map(([id]) => io.sockets.connected[id])
}

If you want to emit something to them , use this :

getSockets('room name').forEach(socket => socket.emit('event name', data))
查看更多
登录 后发表回答