0
0
Flaskframework~5 mins

Flask-SocketIO setup

Choose your learning style9 modes available
Introduction

Flask-SocketIO lets your Flask app talk to web browsers in real time. It helps send and receive messages instantly without refreshing the page.

You want to build a chat app where messages appear instantly.
You need live updates on a dashboard without reloading the page.
You want to create a game that updates players in real time.
You want to notify users immediately when something changes.
You want to handle real-time collaboration like shared editing.
Syntax
Flask
from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app)

Import SocketIO from flask_socketio to add real-time features.

Create a SocketIO object by passing your Flask app to it.

Examples
This example runs the app with debug mode on for easier development.
Flask
from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app, debug=True)
This example allows connections from any origin, useful for testing with different clients.
Flask
from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins='*')

if __name__ == '__main__':
    socketio.run(app)
Sample Program

This simple Flask app uses Flask-SocketIO to connect with the browser. When the page loads, the browser sends a message to the server. The server prints it and replies back. The browser then shows the server's reply on the page.

Flask
from flask import Flask, render_template_string
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

html = '''
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Flask-SocketIO Test</title>
  <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const socket = io();
      socket.on('connect', () => {
        console.log('Connected to server');
        socket.emit('my_event', {data: 'Hello Server!'});
      });
      socket.on('my_response', msg => {
        const p = document.createElement('p');
        p.textContent = 'Server says: ' + msg.data;
        document.body.appendChild(p);
      });
    });
  </script>
</head>
<body>
  <h1>Flask-SocketIO Setup Test</h1>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(html)

@socketio.on('my_event')
def handle_my_event(json):
    print('Received:', json)
    emit('my_response', {'data': 'Got your message!'})

if __name__ == '__main__':
    socketio.run(app, debug=True)
OutputSuccess
Important Notes

Make sure to install flask-socketio with pip install flask-socketio.

Use the socketio.run(app) method instead of app.run() to enable WebSocket support.

Include the Socket.IO client script in your HTML to connect from the browser.

Summary

Flask-SocketIO adds real-time communication to Flask apps.

Set it up by creating a SocketIO object with your Flask app.

Use socketio.run(app) to run your app with WebSocket support.