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:

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:

Key Components:

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:

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:

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