How to Use Flask-SocketIO for Real-Time Web Communication
To use
flask-socketio, install it via pip, create a SocketIO instance with your Flask app, and define event handlers using @socketio.on decorators. Run your app with socketio.run(app) to enable real-time WebSocket communication.Syntax
The basic syntax involves importing SocketIO from flask_socketio, initializing it with your Flask app, and defining event handlers with decorators.
SocketIO(app): Wraps your Flask app to add WebSocket support.@socketio.on('event_name'): Decorator to listen for events from clients.socketio.emit('event_name', data): Sends events to clients.socketio.run(app): Runs the app with SocketIO support.
python
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) @socketio.on('message') def handle_message(msg): print('Received message:', msg) socketio.emit('response', {'data': 'Message received!'}) if __name__ == '__main__': socketio.run(app)
Example
This example shows a simple Flask app using Flask-SocketIO to receive a message from a client and send a response back in real time.
python
from flask import Flask, render_template_string from flask_socketio import SocketIO, send app = Flask(__name__) socketio = SocketIO(app) html = ''' <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Flask-SocketIO Example</title> <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { const socket = io(); socket.on('connect', () => { socket.send('Hello from client!'); }); socket.on('message', data => { const p = document.createElement('p'); p.textContent = 'Server says: ' + data; document.body.appendChild(p); }); }); </script> </head> <body> <h1>Flask-SocketIO Demo</h1> </body> </html> ''' @app.route('/') def index(): return render_template_string(html) @socketio.on('message') def handle_message(msg): print('Received:', msg) send('Message received!') if __name__ == '__main__': socketio.run(app, debug=True)
Output
When you open the page, the client sends 'Hello from client!' to the server, which prints it in the console and replies with 'Message received!' shown on the page.
Common Pitfalls
- Not running the app with
socketio.run(app)causes WebSocket features to not work. - Forgetting to include the Socket.IO client script in HTML breaks client-server communication.
- Using Flask's
app.run()instead ofsocketio.run()disables SocketIO events. - Not handling CORS can block connections; configure
SocketIO(app, cors_allowed_origins='*')if needed.
python
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) # Wrong: Using app.run disables SocketIO # if __name__ == '__main__': # app.run() # Right: if __name__ == '__main__': socketio.run(app)
Quick Reference
Here is a quick summary of key Flask-SocketIO methods and decorators:
| Method/Decorator | Purpose |
|---|---|
| SocketIO(app) | Initialize SocketIO with Flask app |
| @socketio.on('event') | Listen for client events |
| socketio.emit('event', data) | Send event to clients |
| socketio.send(data) | Send a default 'message' event |
| socketio.run(app) | Run Flask app with SocketIO support |
| socketio.disconnect() | Disconnect a client connection |
Key Takeaways
Initialize Flask-SocketIO with your Flask app using SocketIO(app).
Define event handlers with @socketio.on decorators to handle real-time events.
Always run your app with socketio.run(app) to enable WebSocket support.
Include the Socket.IO client script in your HTML to connect from browsers.
Configure CORS if your client and server run on different origins.