room broadcast vs sockets emit - are they the same?

前端 未结 1 1813
南方客
南方客 2021-01-29 09:32

I\'m using my own rooms implementation in Socket.io (got my own Room/Player classes), since I need to perform several filters the room. For now, I save all sockets inside \"play

相关标签:
1条回答
  • 2021-01-29 10:18

    As you can see by looking at the code for the socket.io adapter .broadcast() on GitHub, all socket.io is doing is looping over a list of sockets and sending a packet to each one (see code below).

    So, if your code is doing something similar, then performance would likely be something similar.

    Where you might notice a feature difference is if you are using a custom adapter such as the redis adapter that is used with clustering, then the logic of broadcasting to users connected to different servers would be handled for you by the built-in adapter, but may be something you'd have to implement yourself if doing your own broadcast.

    Here's the socket.io-adapter version of .broadcast():

    Adapter.prototype.broadcast = function(packet, opts){
      var rooms = opts.rooms || [];
      var except = opts.except || [];
      var flags = opts.flags || {};
      var packetOpts = {
        preEncoded: true,
        volatile: flags.volatile,
        compress: flags.compress
      };
      var ids = {};
      var self = this;
      var socket;
    
      packet.nsp = this.nsp.name;
      this.encoder.encode(packet, function(encodedPackets) {
        if (rooms.length) {
          for (var i = 0; i < rooms.length; i++) {
            var room = self.rooms[rooms[i]];
            if (!room) continue;
            var sockets = room.sockets;
            for (var id in sockets) {
              if (sockets.hasOwnProperty(id)) {
                if (ids[id] || ~except.indexOf(id)) continue;
                socket = self.nsp.connected[id];
                if (socket) {
                  socket.packet(encodedPackets, packetOpts);
                  ids[id] = true;
                }
              }
            }
          }
        } else {
          for (var id in self.sids) {
            if (self.sids.hasOwnProperty(id)) {
              if (~except.indexOf(id)) continue;
              socket = self.nsp.connected[id];
              if (socket) socket.packet(encodedPackets, packetOpts);
            }
          }
        }
      });
    };
    
    0 讨论(0)
提交回复
热议问题