Flask-Sock provides WebSocket support for Flask applications, enabling real-time, bi-directional communication. Unlike other solutions, it works directly with the Flask development web server and does not require a greenlet-based server like gevent or eventlet for basic operation. It is also compatible with production WSGI servers such as Gunicorn (with threading), Eventlet, or Gevent. The current version is 0.7.0, with a periodic release cadence.
pip install flask-sockVerified import paths — ran on the pinned version, not inferred.
This quickstart sets up a basic Flask application with a WebSocket endpoint that echoes back any received message. Instantiate `Flask` and `Sock`, then use the `@sock.route()` decorator to define WebSocket handlers. The `ws` object within the handler provides `receive()` and `send()` methods for communication.
Upgrade your Flask installation to version 2.0.0 or higher (`pip install 'Flask>=2.0.0'`).
Use the `--threads` option with Gunicorn to allow a single worker to handle multiple connections concurrently.
Configure `app.config['SOCK_SERVER_OPTIONS'] = {'ping_interval': 25}` in your Flask application to maintain active connections and prevent timeouts for idle clients.Run `pip install flask-sock` to install the library.
Ensure your Flask application is running with a compatible WSGI server (like Gunicorn with threads, Eventlet, or Gevent for production) and that your client's WebSocket URL is correct. For development, ensure Flask and Werkzeug are updated to versions 2.0+ which offer better WebSocket support.
Instead of `sock.register_blueprint()`, define `sock.route` decorators directly on the `Sock` object, or pass the blueprint instance to the `sock.route` decorator's `bp` argument.
Implement proper error handling (e.g., try-except blocks) around `ws.receive()` and `ws.send()` calls to gracefully handle disconnections. Ensure any stored WebSocket objects are removed from active lists when a client disconnects.
Check server-side logs for more specific error messages. If it's a CORS issue, configure `cors_allowed_origins` (if using Flask-SocketIO) or ensure your client's origin is permitted. Verify the client is using the correct WebSocket URL and protocol (e.g., `ws://` or `wss://`).