Overriding socket.io's emit and on?

前端 未结 4 571
礼貌的吻别
礼貌的吻别 2020-12-07 19:30

During development, it helps me greatly to be able to see what packets arrive and gets sent. This is possible on the server side with logger. On the client end, however, the

相关标签:
4条回答
  • 2020-12-07 19:42

    There is a module called socket.io-wildcard which allows using wildcards on client and server side, no need to overwrite anything anymore

    var io         = require('socket.io')();
    var middleware = require('socketio-wildcard')();
    
    io.use(middleware);
    
    io.on('connection', function(socket) {
      socket.on('*', function(){ /* … */ });
    });
    
    io.listen(8000);
    
    0 讨论(0)
  • 2020-12-07 19:51

    Works, tested:

    var _emit = socket.emit;
        _onevent = socket.onevent;
    
        socket.emit = function () { //Override outgoing
            //Do your logic here
            console.log('***', 'emit', arguments);
            _emit.apply(socket, arguments);
        };
    
        socket.onevent = function (packet) { //Override incoming
            var args = packet.data || [];
            //Do your logic here
            console.log('***', 'onevent', packet);
            _onevent.call(socket, packet);
        };
    
    0 讨论(0)
  • 2020-12-07 19:55

    To override socket.on you actually need to override socket.$emit.

    Following example works both client and server-side (tested on socket.io 0.9.0):

    (function() {
      var emit = socket.emit;
      socket.emit = function() {
        console.log('***','emit', Array.prototype.slice.call(arguments));
        emit.apply(socket, arguments);
      };
      var $emit = socket.$emit;
      socket.$emit = function() {
        console.log('***','on',Array.prototype.slice.call(arguments));
        $emit.apply(socket, arguments);
      };
    })();
    
    0 讨论(0)
  • 2020-12-07 20:06
    <script src="/socket.io/socket.io.js"></script>
    <script>
      (function() {
    
          var _origEmit = socket.emit;
          socket.emit = function() {
             console.log(arguments);
             _origEmit.apply(null, Array.prototype.slice.call(arguments));
          };
    
    
      })();
    </script>
    
    0 讨论(0)
提交回复
热议问题