0
0
Flaskframework~5 mins

Broadcasting to clients in Flask

Choose your learning style9 modes available
Introduction

Broadcasting lets your server send messages to many users at once. It helps keep everyone updated in real time.

You want to show live chat messages to all users instantly.
You need to update a dashboard with live data for many viewers.
You want to send notifications to all connected clients at the same time.
You are building a multiplayer game where players see each other's moves live.
Syntax
Flask
from flask import Flask
from flask_socketio import SocketIO, emit

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

# To broadcast a message to all clients
socketio.emit('event_name', {'data': 'message'}, broadcast=True)

Use broadcast=True to send to all connected clients.

Flask-SocketIO is a popular extension to handle real-time communication.

Examples
Sends a chat message to all connected clients.
Flask
socketio.emit('chat_message', {'msg': 'Hello everyone!'}, broadcast=True)
Broadcasts an update event with a count value to all clients.
Flask
socketio.emit('update', {'count': 10}, broadcast=True)
Sample Program

This Flask app sends a welcome message to each client when they connect. When you visit /broadcast, it sends a broadcast message to all connected clients.

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

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

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

@socketio.on('connect')
def handle_connect():
    emit('message', {'msg': 'Welcome!'}, broadcast=False)

@app.route('/broadcast')
def broadcast_message():
    socketio.emit('message', {'msg': 'This is a broadcast message!'}, broadcast=True)
    return 'Broadcast sent!'

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

Clients must use Socket.IO on the frontend to receive broadcast messages.

Broadcasting can cause more network traffic; use it wisely.

Test broadcasts with multiple clients connected to see real-time updates.

Summary

Broadcasting sends messages from server to all connected clients at once.

Use Flask-SocketIO and broadcast=True to enable broadcasting.

Great for live chats, notifications, and real-time updates.