python-3.xsocket.iosanicpython-socketio

Sanic with websocket and SocketIO. Which one to use?


Using Sanic, you can handle websockets connections using @app.websocket('/socket.io/') but the protocol used in Socket.io is specific.

Python has Python-Socketio as a module to handle Socket.Io specific communications, but they recommend to use the code like this :

sio = socketio.AsyncServer(async_mode='sanic')
app = Sanic()
sio.attach(app)

@sio.on('connect')
def on_connect():
    ...

So, which one should be used? Should we implement SocketIo protocol inside @app.websocket from Sanic, or should we ignore this and directly use the implementation from SocketIo?

I'm asking for both rapidity and best practice here. If the best decision is to go with @app.websocket, how can we set up Socket.io inside the Sanic handler?


Solution

  • The Socket.IO protocol is very complex, it will take you a decent amount of time to implement it all manually in the websocket route. Also note that Socket.IO uses the same route for HTTP and WebSocket, something that I understand it is not possible to do (easily, at least) with Sanic.

    The python-socketio package integrates with many frameworks, including Sanic to implement all the details of the Socket.IO protocol.