Socket.io: How to count clients in a room with Socket.io-redis adapter

后端 未结 3 563
执念已碎
执念已碎 2021-02-05 14:19

I start building chat server using Socket.io with multiple nodes. It uses Socket.io-redis to connect all servers together and rooms for messaging.

When a client connects

3条回答
  •  误落风尘
    2021-02-05 15:17

    As of this writing:

    The redis adapter extends the base adapter, but it only overrides/adds the following properties:

    • onmessage
    • broadcast
    • add
    • del
    • delAll

    With this code of yours:

    io.sockets.adapter.rooms["CLIENT_1"];
    

    you are querying the rooms property. This wasn't overridden by the redis adapter, so you're actually querying the base adapter, which only knows about rooms/clients in the current process.

    Why didn't the redis adapter override the rooms property? Because in order to match the exact call signature above, it would have to query the redis instance to construct an object containing all rooms and connections every time the property is accessed. Not good. (That is unless you can figure out how to compute object values at the time their values are queried.)

    If you want to get the number of connections to the "CLIENT_1" room across all processes in the cluster, you'll have to add that functionality to the adapter itself with a method like this:

    /**
       * Count the number of connections in a room.
       *
       * @param {String} room id
       * @param {Function} callback (optional)
       * @api public
       */
    
      Redis.prototype.numClients = function(room, fn){ ... }
    

    wherein you'll query the redis db instance.

    IMO, this should be part of the base adapter interface for all other adapters to implement. It's a common problem.

提交回复
热议问题