Flask-SocketIO

5.6.1 · active · verified Fri Apr 10

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.

Warnings

Install

Imports

Quickstart

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.

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'my_secret_key'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('my event')
def handle_my_custom_event(json):
    print('received json: ' + str(json)) # Logs to server console
    emit('my response', json) # Sends a response back to the client that sent it

@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)
    emit('my response', {'data': message}, broadcast=True) # Broadcasts to all connected clients

if __name__ == '__main__':
    # For development, socketio.run() replaces app.run()
    # For production, install eventlet or gevent for async workers
    socketio.run(app, debug=True)

view raw JSON →