Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Flask Web Sockets
Next article icon

Flask Web Sockets

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

FlaskWebSocketChat-Profile1
Chat broadcasting

Next Article
Flask Web Sockets

P

prajjqv52
Improve
Article Tags :
  • Python
  • Web Technologies
  • python
  • Python Flask
  • Flask Projects
Practice Tags :
  • python
  • python

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 socke
    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,
    7 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
    3 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
    3 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences