Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io : How do I handle all incoming messages on the server?

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.

like image 338
Joshua Avatar asked Jan 25 '12 10:01

Joshua


People also ask

How many messages can Socket.IO handle?

It should handle at least 4-6 concurrent threads. I have created a load test, 100000 different events distributed under 1000 rooms with 5 request per second querying db. It was working fine. Almost 40% RAM and 250% CPU was max laod.

How many Socket.IO connections can a server handle?

Once you reboot your machine, you will now be able to happily go to 55k concurrent connections (per incoming IP).

How do I monitor Socket.IO traffic?

Use Monitor.io to observe connections and replay messages When you add it to your Node. js application, it provides a monitoring interface that you can access remotely by opening a Telnet connection to a particular port. It shows a list of active Socket.io client connections for your application.


2 Answers

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();
 });
});
like image 76
Liam Avatar answered Oct 02 '22 07:10

Liam


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));       
};
like image 41
Ganesh Kumar Avatar answered Oct 02 '22 07:10

Ganesh Kumar