Flask and Flask-SocketIO: Implementing Real-Time WebSockets for Fullstack Applications

Modern web applications often require real-time capabilities—think chat apps, live notifications, collaborative editing, or dynamic dashboards. While Flask is a powerful micro-framework for building APIs and web apps, it’s traditionally built for request-response communication. To bring real-time functionality into your Flask fullstack application, Flask-SocketIO is the tool of choice.

In this blog, we’ll explore how to implement real-time WebSocket communication in a Flask application using Flask-SocketIO, covering setup, communication flow, and use cases.


What is Flask-SocketIO?

Flask-SocketIO is an extension that brings WebSocket support to Flask using Socket.IO, a JavaScript library for real-time web applications. It provides bi-directional communication between clients and the server, going beyond traditional HTTP.

Unlike polling or long-polling, WebSockets keep a persistent connection open, enabling fast, event-driven communication.


Use Cases for Real-Time Features

Live chat applications

Real-time notifications and alerts

Collaborative tools (e.g., Google Docs-like editors)

Stock price or IoT sensor data streaming

Gaming applications


Setting Up Flask with Flask-SocketIO

Step 1: Install Dependencies

bash


pip install flask flask-socketio eventlet

eventlet is a recommended async worker for Flask-SocketIO.


Step 2: Basic Flask-SocketIO App

Create a file called app.py:


python


from flask import Flask, render_template

from flask_socketio import SocketIO, send


app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app)


@app.route('/')

def index():

    return render_template('index.html')


@socketio.on('message')

def handle_message(msg):

    print('Received message: ' + msg)

    send(msg, broadcast=True)


if __name__ == '__main__':

    socketio.run(app, debug=True)


Step 3: Create Frontend HTML with Socket.IO

Create a simple HTML file: templates/index.html


html


<!DOCTYPE html>

<html>

<head>

    <title>Flask SocketIO Chat</title>

    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>

</head>

<body>

    <h2>Chat Room</h2>

    <input id="messageInput" type="text" placeholder="Type message..." />

    <button onclick="sendMessage()">Send</button>

    <ul id="messages"></ul>


    <script>

        var socket = io();


        socket.on('connect', function () {

            console.log('Connected to server');

        });


        socket.on('message', function (msg) {

            const li = document.createElement('li');

            li.textContent = msg;

            document.getElementById('messages').appendChild(li);

        });


        function sendMessage() {

            const input = document.getElementById('messageInput');

            socket.send(input.value);

            input.value = '';

        }

    </script>

</body>

</html>


How It Works

When the client connects, a persistent WebSocket connection is established.

Any message sent using socket.send() from the client is received by the server in the @socketio.on('message') handler.

The server broadcasts the message to all connected clients using broadcast=True.

Deployment Note

To run Flask-SocketIO in production, use:


bash

Copy

Edit

socketio.run(app, host='0.0.0.0', port=5000)

Or use Gunicorn with eventlet:


bash

Copy

Edit

gunicorn -k eventlet -w 1 app:app


Conclusion

By integrating Flask-SocketIO into your fullstack Flask app, you can easily implement real-time features such as chat, notifications, and live updates. This enables a more dynamic and interactive user experience compared to traditional request/response models. Whether you’re building a lightweight messaging app or a complex dashboard, WebSockets via Flask-SocketIO will help bring your application to life—instantly.

Learn FullStack Python Training Course

Read More : Flask with Celery: Building Asynchronous APIs for Heavy Tasks

Read More : Fullstack Flask API Testing: Automating API Tests with Postman

Read More : Flask API Authentication with OAuth 2.0 and JWT

Visit Quality Thought Training Institute

Get Direction


Comments

Popular posts from this blog

Using ID and Name Locators in Selenium Python

Tosca vs Selenium: Which One to Choose?

Implementing Rate Limiting in Flask APIs with Flask-Limiter