SocketIO + Flask Detect Disconnect
Asked Answered
P

1

7

I had a different question here, but realized it simplifies to this: How do you detect when a client disconnects (closes their page or clicks a link) from a page (in other words, the socket connection closes)? I want to make a chat app with an updating user list, and I’m using Flask on Python. When the user connects, the browser sends a socket.emit() with an event and username passed in order to tell the server a new user exists, after which the server will message all clients with socket.emit(), so that all clients will append this new user to their user list. However, I want the clients to also send a message containing their username to the server on Disconnect. I couldn’t figure out how to get the triggers right. Note: I’m just using a simple html file with script tags for the page, I’m not sure how to add a JS file to go along with the page, though I can figure it out if it’s necessary for this.

Polytonality answered 27/3, 2020 at 3:41 Comment(0)
P
7

Figured it out. socket.on('disconnect') did turn out to be right, however by default it pings each user only once a minute or so, meaning it took a long time to see the event.

Polytonality answered 10/4, 2020 at 2:38 Comment(3)
This is impotent information for me! Thanks! Please add information how to change default ping resolution time from 1 minute.Peacetime
I would like to see your solution aswellStrove
Socket.IO uses long polling by default and not web sockets (unfortunately). This is because Flask itself cannot support web sockets natively (But it seems like Flask 2.0 has taken some steps to improve support). To run websockets using Flask-SocketIO you'll need to run Flask via a server such as gunicorn using the eventlet or gevent workers. flask-socketio.readthedocs.io/en/latest/deployment.htmlFusco

© 2022 - 2024 — McMap. All rights reserved.