miguelgrinberg / flask-sock

Modern WebSocket support for Flask.
MIT License
272 stars 24 forks source link

The number of connections #41

Closed hongbo-miao closed 1 year ago

hongbo-miao commented 1 year ago

I am hoping to know how many clients currently connected.

websocket has a wss.clients.size which can be used directly https://github.com/websockets/ws/issues/1087 Is there anything similar?

I am also thinking to use connection events to count myself. Does flask-sock support connection events like Flask-SocketIO's connection events? I tried to find in the doc and other issue tickets, also read some source code, but didn't find. Did I miss anything?

Or any other suggestion would be appreciate. Thanks! 😃

miguelgrinberg commented 1 year ago

This extension does not count or keep track of clients, that is left for the application to implement.

A separate connection request does not make sense in this extension, you can consider your handler function as the connection request and count your clients there. For example:

clients = 0

@sock.route('/ws')
def websocket(ws):
    global clients
    clients += 1
    try:
        # your logic here
    finally:
        clients -= 1

Note that this solution is very simplistic and would not work for a real-world application that is deployed with multiple server workers. For a multi-worker deployment you will need to replace the clients global variable with a value stored in a database that is accessible to all the worker processes.

hongbo-miao commented 1 year ago

Thank you so much @miguelgrinberg for explaining!