覆盖socket.io的发射和继续? [英] Overriding socket.io's emit and on?

查看:68
本文介绍了覆盖socket.io的发射和继续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发过程中,能够查看到达和发送哪些数据包对我有很大帮助.在使用记录器的服务器端,这是可能的.但是,在客户端上没有记录器.我发现自己到处都是个乱七八糟的console.log.

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, there is no logger. I find myself to be littering console.log all over the place.

是否可以用console.log(arguments)覆盖socket.emit和socket.on?如果我可以在我的套接字之前覆盖它,那将是非常优雅的.

Is it possible to override socket.emit and socket.on with console.log(arguments)? If I can override this at the before my socket, it would be really elegant.

有人建议我改写解析器.

Somebody advised me to override the Parser instead.

您的2美分是多少?

编辑

我尝试了加藤的建议,并写了以下内容:

I tried Kato's suggestion and wrote the following:

var _origEmit = socket.emit;
socket.emit = function() { 
  console.log("SENT", Array.prototype.slice.call(arguments));
  _origEmit.call(socket, arguments);
};

这有效.但是,socket.on并没有那么多.我的策略是使用console.log包装每个回调.如果您了解python,那有点像将函数装饰器放在console.log参数的回调中.

This works. However, Not so much with socket.on. My strategy is to wrap each callback with a console.log. If you know python, it's kind of like putting function decorators on the callbacks that console.log the arguments.

(function(socket) { 
var _origOn = socket.on;
socket.on = function() { 
  var args = Array.prototype.slice.call(arguments)
    , handlerType = args[0]
    , originalCallback = args[1];

  var wrappedCallback = function() { 
    // replace original callback with a function 
    // wrapped around by console.log
    console.log("RECEIVED", Array.prototype.slice.call(arguments));
    originalCallback.call(socket, arguments);
  }

  _origOn.call(socket, [handlerType, wrappedCallback]);
}

任何人都可以指出为什么猴子修补socket.on无法正常工作?

Any one can point to why monkey patching socket.on is not working?

推荐答案

要覆盖 socket.on ,您实际上需要覆盖 socket.$ emit .

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

以下示例在客户端和服务器端均可使用(在socket.io 0.9.0上测试):

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);
  };
})();

这篇关于覆盖socket.io的发射和继续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆