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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask WebSocket Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
var socket = io();
var username = prompt("Enter your name:"); // Ask for username
socket.emit("join", username); // Notify server of new user
// Listen for messages from server
socket.on("message", function(data) {
var messages = document.getElementById("messages");
messages.innerHTML += `<p>${data}</p>`;
});
// Function to send messages
function sendMessage() {
var msgInput = document.getElementById("msg");
var message = msgInput.value;
socket.send(message);
msgInput.value = "";
}
</script>
</head>
<body>
<h2>Flask WebSocket Chat</h2>
<input id="msg" type="text" placeholder="Enter your message">
<button onclick="sendMessage()">Send</button>
<div id="messages"></div>
</body>
</html>
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:
Chat broadcasting
Similar Reads
Web-Socket in Node
WebSockets in Express.js and Node.js enable real-time, two-way communication between a website and its server. This allows for features like live chat, instant updates, and interactive experiences. WebSockets maintain a persistent connection, unlike typical web requests.Libraries such as ws and sock
5 min read
Web Server and Its Types
A web server is a systemâeither software, hardware, or bothâthat stores, processes, and delivers web content to users over the Internet using the HTTP or HTTPS protocol. When a userâs browser sends a request (like visiting a website), the web server responds by delivering the appropriate resources s
7 min read
Flask - HTTP Method
In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Before starting let's understand the basic terminologies: GET: to request data from the server.POST: to submit data to be processed to the server.PUT: replaces the entire resource with new data. If
5 min read
Flask Middlewares
Middleware is a powerful concept in web applications that allows you to process requests and responses before they reach the main application logic. In Flask, middleware functions sit between the client request and the final response, enabling tasks like logging, authentication, request modification
5 min read
Sockets | Python
What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX o
3 min read
Node.js Web Server
A NodeJS web server is a server built using NodeJS to handle HTTP requests and responses. Unlike traditional web servers like Apache or Nginx, which are primarily designed to give static content, NodeJS web servers can handle both static and dynamic content while supporting real-time communication.
6 min read
Learn to use Websockets with Django
Django Channels is an extension of the Django framework that allows for handling WebSockets, HTTP2, and other protocols. It integrates with Djangoâs existing ORM and works seamlessly alongside Django views. In this tutorial, we will create a small Django project that displays "GeeksforGeeks" on the
4 min read
Python Flask - Request Object
In a Flask App, we have our own Webpage (Client) and a Server. The Server should process the data. Â The Request, in Flask, is an object that contains all the data sent from the Client to Server. This data can be recovered using the GET/POST Methods. POST is used when your application expects user in
5 min read
Node.js agent.maxSockets Method
The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ârequire(âhttpâ)â). HTTP message headers are represented as JSON Format. The agent.maxSockets (Added in v0.3.6) method is an inbuilt appli
2 min read
How To Use WebSocket With FastAPI
In this article, we will see what a WebSocket is, why we need Websocket, and how Websocket can be used to make real-time applications. We will see HTTP requests getting upgraded to web socket and how it will allow the server to send data to the client without the client having to send multiple HTTP
5 min read