{"id":2510,"library":"flask-socketio","title":"Flask-SocketIO","description":"Flask-SocketIO is a Flask extension that enables real-time bidirectional communication between clients and servers using the Socket.IO protocol. It provides features like event-based communication, rooms for grouping clients, namespaces for organization, and automatic reconnection. The library is actively maintained, with frequent releases, and its current version is 5.6.1.","status":"active","version":"5.6.1","language":"en","source_language":"en","source_url":"https://github.com/miguelgrinberg/flask-socketio","tags":["flask","socket.io","websockets","realtime","async"],"install":[{"cmd":"pip install Flask-SocketIO","lang":"bash","label":"Basic Installation"},{"cmd":"pip install Flask-SocketIO[eventlet]","lang":"bash","label":"With Eventlet (Async Server)"},{"cmd":"pip install Flask-SocketIO[gevent]","lang":"bash","label":"With Gevent (Async Server, Recommended)"},{"cmd":"pip install Flask-SocketIO redis","lang":"bash","label":"With Redis Message Queue (for Scaling)"}],"dependencies":[{"reason":"Asynchronous web server for production deployments, providing WebSocket support. Less actively maintained than gevent.","package":"eventlet","optional":true},{"reason":"Recommended asynchronous web server for production deployments, providing WebSocket support and better performance than eventlet.","package":"gevent","optional":true},{"reason":"Required for using Redis as a message queue for inter-process communication when deploying multiple workers or emitting from external processes.","package":"redis","optional":true},{"reason":"Required for using RabbitMQ or other Kombu-supported message queues for inter-process communication when deploying multiple workers or emitting from external processes.","package":"kombu","optional":true},{"reason":"Required for using Kafka as a message queue for inter-process communication when deploying multiple workers or emitting from external processes.","package":"kafka-python","optional":true}],"imports":[{"symbol":"SocketIO","correct":"from flask_socketio import SocketIO"},{"note":"The context-aware `send()` and `emit()` (for use inside event handlers) are typically imported directly. The `socketio.send()` and `socketio.emit()` methods are for server-originated messages outside a request context.","wrong":"socketio.send() within an event handler context without explicit import","symbol":"send","correct":"from flask_socketio import send"},{"symbol":"emit","correct":"from flask_socketio import emit"}],"quickstart":{"code":"from flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'my_secret_key'\nsocketio = SocketIO(app)\n\n@app.route('/')\ndef index():\n    return render_template('index.html')\n\n@socketio.on('my event')\ndef handle_my_custom_event(json):\n    print('received json: ' + str(json)) # Logs to server console\n    emit('my response', json) # Sends a response back to the client that sent it\n\n@socketio.on('message')\ndef handle_message(message):\n    print('received message: ' + message)\n    emit('my response', {'data': message}, broadcast=True) # Broadcasts to all connected clients\n\nif __name__ == '__main__':\n    # For development, socketio.run() replaces app.run()\n    # For production, install eventlet or gevent for async workers\n    socketio.run(app, debug=True)\n","lang":"python","description":"This quickstart demonstrates a basic Flask-SocketIO application. It initializes a Flask app, wraps it with `SocketIO`, and defines event handlers for `my event` and `message`. The `my event` handler echoes data back to the sender, while the `message` handler broadcasts to all connected clients. Crucially, `socketio.run(app)` is used instead of `app.run()` to start the server, enabling WebSocket support. For production, asynchronous workers like eventlet or gevent are recommended."},"warnings":[{"fix":"Ensure your client-side Socket.IO library (e.g., JavaScript client) is compatible with Socket.IO protocol v3 or later. Upgrade `socket.io-client` in your frontend project (e.g., `npm install socket.io-client@^4.0.0`).","message":"Flask-SocketIO 5.x adopted backwards-incompatible changes in the Socket.IO protocol (Socket.IO v3+). This requires the client-side Socket.IO JavaScript library to also be upgraded to a compatible version (e.g., 3.x or 4.x). Mismatched protocol versions will result in connection failures and '400' errors.","severity":"breaking","affected_versions":"5.0.0 and later"},{"fix":"Replace `app.run()` with `socketio.run(app)`. Additionally, for production, install an asynchronous worker (e.g., `pip install gevent`).","message":"For production deployments, `socketio.run(app)` should always be used to start the server instead of `app.run()`. `socketio.run()` ensures that an appropriate asynchronous web server (like Eventlet or Gevent, if installed) is used, which is necessary for proper WebSocket functionality and performance. Using `app.run()` will default to Flask's built-in development server, which lacks robust WebSocket support and is not suitable for production.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Install either `gevent` (`pip install gevent`) or `eventlet` (`pip install eventlet`). `gevent` is recommended. If using a message queue, 'monkey patching' of the standard library might be required by calling `eventlet.monkey_patch()` or `from gevent import monkey; monkey.patch_all()` at the very top of your main script.","message":"Asynchronous workers (like `gevent` or `eventlet`) are crucial for performance and proper WebSocket handling in production environments. Without them, Flask-SocketIO defaults to Python's threading, which can lead to performance bottlenecks and unresponsiveness under high load. `gevent` is generally preferred over `eventlet` as `eventlet` is in maintenance mode.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Configure a message queue (e.g., `socketio = SocketIO(app, message_queue='redis://localhost:6379')`) and ensure your load balancer uses 'sticky sessions' (e.g., `ip_hash` in Nginx). Install the corresponding message queue package (e.g., `pip install redis`).","message":"When running multiple Flask-SocketIO server instances behind a load balancer (for scaling), a message queue (such as Redis or RabbitMQ) is mandatory for coordinating operations like broadcasting and rooms. Without a message queue, events will only be delivered to clients connected to the specific server instance that emitted the event. Additionally, the load balancer *must* be configured for 'sticky sessions' to ensure a client's requests are always routed to the same worker.","severity":"breaking","affected_versions":"All versions"},{"fix":"Be aware of this session isolation. If shared session state between HTTP and SocketIO is critical, consider server-side session extensions (e.g., Flask-Session, Flask-KVSession) and initialize `SocketIO(app, manage_session=False)` to allow Flask's session management to be used.","message":"Modifications to the Flask `session` object within SocketIO event handlers create a 'fork' of the session that is independent of the session seen by regular HTTP routes. Changes made in a SocketIO handler will persist for subsequent SocketIO handlers on the same connection but will *not* be visible to Flask HTTP route handlers (and vice-versa). This is due to how sessions are saved, requiring HTTP request/response cycles that don't exist in a SocketIO connection.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For any potentially blocking operations, offload them to a background task or thread using `socketio.start_background_task()` or a dedicated task queue (e.g., Celery). For example: `socketio.start_background_task(my_long_running_function, arg1, arg2)`.","message":"Blocking operations (e.g., long database queries, heavy computations, network calls) within SocketIO event handlers will block the entire server process when using an asynchronous framework like Gevent or Eventlet, leading to severe performance issues and unresponsiveness.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}