Socket.io : How do I handle all incoming messages

2019-06-15 21:39发布

I want to be able to handle all messages that are coming in from clients in a single handler.

Example client code:

var socket = io.connect('http://localhost');
socket.emit('news', { hello: 'test' });
socket.emit('chat', { hello: 'test' });

Example server code:

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

I'd like to be able to log every message even if its sent on news, chat or whatever other name using emit. Is this possible?

Note: The above server code does not work. There is nothing currently logged. I am just wondering if there is a single event which could be handled for all messages for every emit name.

2条回答
神经病院院长
2楼-- · 2019-06-15 22:17

This is an open issue with Socket.IO.

At this time, if you really need it, you will probably have to fork Socket.IO. See 3rd-Edens comment for how to do it.

查看更多
爷的心禁止访问
3楼-- · 2019-06-15 22:25

That is possible by overriding socket.$emit function

//Original func
var x = socket.$emit;

socket.$emit = function(){
     var event = arguments[0];
     var feed  = arguments[1];

     //Log
     console.log(event + ":" + feed);

    //To pass listener  
    x.apply(this, Array.prototype.slice.call(arguments));       
};
查看更多
登录 后发表回答