Python Socket.io handle all events (catch all events from client)

2.9k Views Asked by At

The documentation for Python Socket.io is here: https://python-socketio.readthedocs.io/en/latest/api.html#asyncserver-class

That is the server class, with 'event' and 'on' methods for handling events. However, those are named events.

How to handle all events from client (catch all) on server side? I've tried .on("*",...) but it didn't work, the asterisk * seems just a string in Python socket.io.

3

There are 3 best solutions below

1
On BEST ANSWER

It doesn't seem to be in the docs explicitly, but you can listen for the 'message' events. Like 'connect' and 'disconnect' it's reserved, and it catches all incoming messages.

0
On

You can use AsyncNamespace class to override trigger_event method.

Dispatch an event to the proper handler method.

In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overridden if special dispatching rules are needed, or if having a single method that catches all events is desired.

class MyCustomNamespace(socketio.AsyncNamespace):
    async def trigger_event(self, event_name, sid, *args):
        print(f"{event_name=}, {sid=}")
        if args:
            print(f"data is {args[0]}")


sio.register_namespace(MyCustomNamespace())
0
On

It seems that with flask_socketio the on("*") event handler to catch all unregistered events doesn't work.

I have no idea if it breaks anything but a workaround is to access python-socketio server object itself, and then use on("*") like:

@sio.server.on('*')
def catch_all(event, sid, *args):
    print(f'catch_all(event={event}, sid={sid}, args={args})')