Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io - how to access unhandled messages?

How can you detect that you received a message on a socket.io connection that you do not have a handler for?

example:

// client
socket.emit('test', 'message');

// server
io.on('connection', function (socket) {
  console.log('connection received...');

  // logs all messages
  socket.conn.on('message', function(data) {
    console.log('this gets every message.');
    console.log('how do I get just the ones without explicit handlers?');
  });

  socket.on('other' function(data) {
    console.log('expected message');
  });
}
like image 229
pe-sean Avatar asked Nov 19 '22 06:11

pe-sean


1 Answers

By accessing the internals of the socket object you can determine what events it is currently listening for. You can use this server-side code to see if the current message is being handled.

io.on('connection', (socket) => {
    console.log('A user connected.');
    socket.on('disconnect', () => {
        console.log('A user disconnected.');
    });
    socket.on('chat', (msg) => {
        console.log('message: ' + msg);
        io.emit('chat', msg);
    });
    socket.conn.on('message', (msg) => {
        if(!Object.keys(socket._events).includes(msg.split('"')[1])) {
            console.log(`WARNING: Unhandled Event: ${msg}`);
        }
    });
}

Once connected I am handling two events, 'disconnect' and 'chat'. After that I define a handler that catches all messages with socket.conn.on(...).

The message it receives is going to be a string that looks something like this: '2["myEventName","param1","param2"]'. By splitting it along the double quotes we can get the event name.

We then peek into the internals of socket to find all the keys of socket._events, which happen to be the event name strings. If this collection of strings includes our event name, then another handler will take care of it, and we don't have to.

You can test it from the console in the browser. Run socket.emit('some other event') there and you should see your warning come up in the server console.

IMPORTANT NOTE: Normally you should not attempt to externally modify any object member starting with an underscore. Also, expect that any data in it is unstable. The underscore indicates it is for internal use in that object, class or function. Though this object is not stable, it should be up to date enough for us to use it, and we aren't modifying it directly.

Tested with SocketIO version 2.2.0 on Chrome.

like image 108
eadsjr Avatar answered Dec 22 '22 19:12

eadsjr