0
0
FlaskHow-ToBeginner · 4 min read

How to Use WebSocket in Flask: Simple Guide with Example

To use WebSocket in Flask, install and use the Flask-SocketIO extension which adds WebSocket support. Define event handlers with @socketio.on decorators and run your app with socketio.run(app) to enable real-time bidirectional communication.
📐

Syntax

Using WebSocket in Flask requires the Flask-SocketIO extension. You create a SocketIO object with your Flask app, then define event handlers using @socketio.on('event_name'). Finally, run the app with socketio.run(app) instead of app.run().

  • SocketIO(app): Wraps your Flask app to add WebSocket support.
  • @socketio.on('event'): Decorator to handle WebSocket events.
  • socketio.emit(): Send messages to clients.
  • socketio.run(app): Runs the app with WebSocket support.
python
from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(msg):
    emit('response', {'data': msg})

if __name__ == '__main__':
    socketio.run(app)
💻

Example

This example shows a simple Flask app using WebSocket to echo messages sent from the client. When the client sends a message, the server responds with the same message wrapped in a JSON object.

python
from flask import Flask, render_template_string
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask WebSocket 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 Server!');
            });
            socket.on('response', data => {
                const p = document.createElement('p');
                p.textContent = 'Server says: ' + data.data;
                document.body.appendChild(p);
            });
        });
    </script>
</head>
<body>
    <h1>Flask WebSocket Echo</h1>
</body>
</html>
'''

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

@socketio.on('message')
def handle_message(msg):
    emit('response', {'data': msg})

if __name__ == '__main__':
    socketio.run(app, debug=True)
Output
Running the app and opening the page shows a heading 'Flask WebSocket Echo'. The client sends 'Hello Server!' on connect, and the page displays 'Server says: Hello Server!' below the heading.
⚠️

Common Pitfalls

  • Not installing flask-socketio or missing dependencies like python-socketio and eventlet or gevent.
  • Using app.run() instead of socketio.run(app) will disable WebSocket support.
  • Forcing WebSocket transport without fallback can cause connection failures in some browsers or networks.
  • Not handling CORS properly when client and server are on different origins.
python
## Wrong way (no WebSocket support):
# app.run()

## Right way:
socketio.run(app)

## Install dependencies:
# pip install flask-socketio eventlet

## Run with eventlet for best support:
# socketio.run(app, host='0.0.0.0', port=5000, debug=True)
📊

Quick Reference

Remember these key points when using WebSocket in Flask:

  • Install flask-socketio and a compatible async server like eventlet.
  • Wrap your Flask app with SocketIO(app).
  • Use @socketio.on('event') to handle WebSocket events.
  • Run your app with socketio.run(app) to enable WebSocket.
  • Use socketio.emit() to send messages to clients.

Key Takeaways

Use Flask-SocketIO extension to add WebSocket support to your Flask app.
Define event handlers with @socketio.on decorators to respond to client messages.
Run your app with socketio.run(app) instead of app.run() for WebSocket functionality.
Install eventlet or gevent for asynchronous WebSocket server support.
Test your WebSocket connection in a browser with client-side Socket.IO script.