Flask Web Sockets (original) (raw)
Last Updated : 23 Jul, 2025
WebSockets enable real-time, bidirectional communication between a client and a server. Unlike traditional HTTP requests, which follow a request-response cycle, WebSockets maintain a persistent connection, allowing instant data exchange.
This is particularly useful for applications like:
- Live chat.
- Notifications.
- Stock price updates.
- Collaborative editing tools.
Flask, being a lightweight framework, does not provide WebSocket support by default, but with the help of **Flask-SocketIO module, we can easily integrate **WebSockets into a Flask application.
Setting Up Flask WebSocket Application
Initialize Flask app and install required packages using the following command:
pip install flask flask-socketio
Flask-SocketIO builds on top of Flask and provides a simple interface for managing WebSocket connections. A typical Flask WebSocket application involves:
- Initializing the Flask app.
- Wrapping the Flask app with SocketIO.
- Defining event handlers using decorators such as @socketio.on().
- Running the app using socketio.run(app).
Key Components:
- **SocketIO(app): This wraps the Flask application to enable WebSocket capabilities.
- **Event Handlers: Functions decorated with @socketio.on('<event_name>') respond to specific WebSocket events.
- **send(): Sends a simple message.
- **emit(): Sends a message to a specific event channel, which can include more complex data.
Building a Real-Time Messaging App with Flask-SocketIO
To understand how to implement Flask-SocketIO in a Flask application, let's build a real-time message broadcasting application. This application will establish WebSocket connections to enable seamless communication between multiple users. Whenever a user sends a message, it will be broadcast to all connected clients in real-time.
We'll use Flask-SocketIO to handle WebSocket events, allowing clients to send and receive messages instantly. This example will demonstrate how to:
- Set up a WebSocket connection in Flask.
- Send and receive messages in real time.
- Broadcast messages to all connected users.
app.py code:
Python `
from flask import Flask, render_template, request from flask_socketio import SocketIO, send, emit, join_room, leave_room
app = Flask(name) app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)
Dictionary to store users and their assigned rooms
users = {}
@app.route('/') def index(): return render_template('index.html')
Handle new user joining
@socketio.on('join') def handle_join(username): users[request.sid] = username # Store username by session ID join_room(username) # Each user gets their own "room" emit("message", f"{username} joined the chat", room=username)
Handle user messages
@socketio.on('message') def handle_message(data): username = users.get(request.sid, "Anonymous") # Get the user's name emit("message", f"{username}: {data}", broadcast=True) # Send to everyone
Handle disconnects
@socketio.on('disconnect') def handle_disconnect(): username = users.pop(request.sid, "Anonymous") emit("message", f"{username} left the chat", broadcast=True)
if name == 'main': socketio.run(app, debug=True)
`
**Explanation:
- ****@socketio.on('connect')** event is triggered when a user connects, sending a welcome message using send().
- ****@socketio.on('message')** event handles incoming messages and broadcasts them to all connected clients using send(message, broadcast=True).
- ****@socketio.on('disconnect'**) event logs when a user leaves the chat.
- **socket.on("message", callback) listens for messages and updates the chat window dynamically.
- Messages are sent using **socket.send(message), which triggers the message event on the server.
index.html code:
Make sure we have created the templates folder in the project folder and inside the template folder create an index.html file, it will serve the frontend and sets up the client-side connection and allows message exchange:
HTML ``
Flask WebSocket Chat