how to list rooms on socket.io nodejs server

孤街醉人 提交于 2019-11-28 05:49:07
Alfred

The short answer:

io.sockets.adapter.rooms

I analysed io:

I got the following output:

{ server: 
   { stack: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ],
     connections: 3,
     allowHalfOpen: true,
     watcher: { host: [Circular], callback: [Function] },
     _events: 
      { request: [Function],
        connection: [Function: connectionListener],
        listening: [Object],
        upgrade: [Object] },
     httpAllowHalfOpen: false,
     cache: {},
     settings: { home: '/', env: 'development', hints: true },
     redirects: {},
     isCallbacks: {},
     _locals: { settings: [Object], app: [Circular] },
     dynamicViewHelpers: {},
     errorHandlers: [],
     route: '/',
     routes: 
      { app: [Circular],
        routes: [Object],
        params: {},
        _params: [],
        middleware: [Function] },
     router: [Getter],
     __usedRouter: true,
     type: 'tcp4',
     fd: 7 },
  namespaces: 
   { '': 
      { manager: [Circular],
        name: '',
        sockets: [Object],
        auth: false,
        flags: [Object],
        _events: [Object] } },
  sockets: 
   { manager: [Circular],
     name: '',
     sockets: { '210837319844898486': [Object] },
     auth: false,
     flags: { endpoint: '', exceptions: [] },
     _events: { connection: [Function] } },
  settings: 
   { origins: '*:*',
     log: true,
     store: 
      { options: undefined,
        clients: [Object],
        manager: [Circular] },
     logger: { colors: true, level: 1 },
     heartbeats: true,
     resource: '/socket.io',
     transports: 
      [ 'websocket',
        'htmlfile',
        'xhr-polling',
        'jsonp-polling' ],
     authorization: [Function],
     'log level': 1,
     'close timeout': 25,
     'heartbeat timeout': 15,
     'heartbeat interval': 20,
     'polling duration': 20,
     'flash policy server': true,
     'flash policy port': 843,
     'destroy upgrade': true,
     'browser client': true,
     'browser client minification': false,
     'browser client etag': false,
     'browser client handler': false,
     'client store expiration': 15 },
  handshaken: 
   { '210837319844898486': 
      { headers: [Object],
        address: [Object],
        time: 'Mon Jul 18 2011 00:53:27 GMT+0200 (CEST)',
        xdomain: false,
        secure: undefined,
        PHPSESSID: '7qo6cht3q0rskhfes4eesb2d05' } },
  connected: { '210837319844898486': true },
  open: { '210837319844898486': true },
  closed: {},
  closedA: [],
  rooms: 
   { '': [ '210837319844898486' ],
     '/public-alfred': [ '210837319844898486' ] },
  roomClients: { '210837319844898486': [ '': true, '/public-alfred': true ] },
  oldListeners: [ [Function] ],
  _events: 
   { 'set:origins': [Function],
     'set:flash policy port': [Function],
     'set:transports': [Function] } }

after joining room "public-alfred" from a single client io.sockets.adapter.rooms contained:

 { '': [ '210837319844898486' ],
         '/public-alfred': [ '210837319844898486' ] }

In a new version of socket.io (1.x), io.sockets.manager.rooms will cause an error. You should use io.sockets.adapter.rooms instead.

As everyone said, in a new version of socket.io (1.x) the rooms can be found at:

    io.sockets.adapter.rooms

This will return something like:

{ 
    'qNADgg3CCxESDLm5AAAA': [ 'qNADgg3CCxESDLm5AAAA': true ],
    'myRoom': [ 'qNADgg3CCxESDLm5AAAA': true,
                '0rCX3v4pufWvQ6uwAAAB': true,
                'iH0wJHGh-qKPRd2RAAAC': true ],  
    '0rCX3v4pufWvQ6uwAAAB': [ '0rCX3v4pufWvQ6uwAAAB': true ],  
    'iH0wJHGh-qKPRd2RAAAC': [ 'iH0wJHGh-qKPRd2RAAAC': true ] 
}

The only room that I want to get is 'myRoom', so I wrote the following function for doing that:

function findRooms() {
    var availableRooms = [];
    var rooms = io.sockets.adapter.rooms;
    if (rooms) {
        for (var room in rooms) {
            if (!rooms[room].hasOwnProperty(room)) {
                availableRooms.push(room);
            }
        }
    }
    return availableRooms;
}

This was kind of confusing for me, hope this helps!

in case you are using

socket.io 2.1.0

and chanced upon this.

in 2.1.0, all the rooms in the server are located in the variable io.sockets.adapter.rooms

//Use Example//

sockets.on('getRooms', function() {
    sockets.emit('rooms', io.sockets.adapter.rooms);
});

You will get the following results.

{ xqfGuWYkKzT9hGgGAAAB: Room { sockets: { xqfGuWYkKzT9hGgGAAAB: true }, length: 1 }, '0Ak9nTjme7bLsD8NAAAC': Room { sockets: { '0Ak9nTjme7bLsD8NAAAC': true }, length: 1 } }

In socketIO version 2.2.0,

  • io.sockets.manager does not exist anymore

You can get all sockets in a specific room using followings 3.

socket.adapter.rooms;
io.sockets.adapter.rooms
io.sockets.adapter.sids

If you are using namespace you should use socket.adapter.rooms to get the room lists.

{ '/userSocket#oXorUiql1GF68dbTAAAB':
   Room {
     sockets: { '/userSocket#oXorUiql1GF68dbTAAAB': true },
     length: 1 
     },
  roomOneName:
   Room {
     sockets: { '/userSocket#oXorUiql1GF68dbTAAAB': true },
     length: 1 
     },
  roomTwoName:
   Room {
     sockets: { '/userSocket#oXorUiql1GF68dbTAAAB': true },
     length: 1 
   } 
}

If io.sockets.adapter is undefined..

I'm using socket.io 1.7.1 (Server).

It seems io.of("......").sockets.adapter is undefined on that version of socket.io. So I used io.adapter.rooms instead and it works.

I was able to find them using socket._events on an open connection.

io.sockets.on('connection', function(socket){
  socket.on('ping', function(data){
    console.log(socket._events);
  });
});

Output:

{
  ping: [Function],
  disconnect: [Function]
}
Object.keys(io.sockets.adapter.rooms)

use this to get all rooms.

I don't have enough reputation to post my comment to the original question, but in addition, if you want to list all the rooms in a namespace, it should be coded like this:

var nsp = io.of('/my-nsp');

var rooms = nsp.adapter.rooms;

This would help so that if a client join a room by:

socket.join('my-room');

You should be able to see your room name when you do console.log(rooms);

I just want to answer an unanswered comment above as I ran into the same issue after I saw mismatched room names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!