Search code examples
sessionwebsocketflask-socketio

How do I catch an event when flask-socketio decides to delete a socketio session?


Heads up: flask-socketio sessions are not User Sessions mentioned below.

I'm restructuring my React app to handle multiple User Sessions defined by a string in the URL. Whenever a browser tab/window connects to the server with the User Session in its URL, I will record it as a connection of that User Session, and multiple connections of the same User Session will be stored in a list.

I found request.sid might be the right thing to identify these connections I mentioned, and I can add the value of request.sid to the list whenever a new connection from a browser tab/window is built. Each tab/window is assigned a different such sid, i.e. socketio session id, and multiple socketio session ids belong to a single User Session of my definition.

However, I don't know when a browser connection is lost due to internet disconnection. Usually, it's handled by heartbeat mechanism, and flask-socketio already has a heartbeat built in, so I'm wondering whether I can catch an event when the built-in heartbeat finally exceeds the expiration time, so that I can go ahead and delete the sid from the connection list.

Any ideas/suggestions for me? Thank you in advance!


Solution

  • You can listen to the disconnect event:

    @socketio.on('disconnect')
    def client_disconnected():
        # remove request.sid from your application state