12

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.

Joshua
  • 3,465
  • 3
  • 28
  • 19

3 Answers3

5

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));       
};
Holger Just
  • 52,918
  • 14
  • 115
  • 123
Ganesh Kumar
  • 1,341
  • 11
  • 18
  • Does this work on incoming messages, because from the function name it suggests it is a function for outgoing messages? – mtsr Jan 29 '12 at 08:38
1

It's even easier on Socket.Io >3 using the socket.onAny(listener):

this.socket.onAny(m => {
    ..
});

This is supported out of the box now as of Socket-io 2.0.4, you simply need to register a middle ware (source from socketio-wildcard):

As of Socket.io v2.0.4 (commit), you can use a socket middleware to catch every incoming Packet, which satisfies most of socketio-wildcard's use cases.

io.on('connection', (socket) => {
  socket.use((packet, next) => {
   // Handler
   next();
 });
});
Liam
  • 27,717
  • 28
  • 128
  • 190
0

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.

mtsr
  • 3,092
  • 1
  • 14
  • 21
  • 2
    Well, this definitely isn't the answer I was hoping for. – Joshua Jan 25 '12 at 17:30
  • Me neither, but that's the current situation. On the other hand, the changes from 3rd-Edens comment are only 3-5 lines and should be easy enough to implement. – mtsr Jan 26 '12 at 08:08