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.
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:
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:
Explanation:
1. Connecting to the Server:
The script loads the Socket.IO client library from a CDN.
var socket = io() establishes a connection to the Flask-SocketIO server.
2. Event Listeners:
Listens for the message event and displays the data in a div with id messages.
Listens for a custom event custom_response and displays the response.
3. Sending Messages:
The sendMessage() function reads input from a text field and sends it to the server using socket.send().
The input field is then cleared for the next message.
Live Demonstration
Run the application using the following command in the terminal and visit the development URL:
python app.py
Below is the GIF of the live demonstration of the application: