from flask_socketio import SocketIO socketio = SocketIO(app) @socketio.on('connect') def handle_connect(): socketio.emit('message', {'data': 'Hello'})
When you emit without specifying a room or namespace from within an event handler such as 'connect', Flask-SocketIO sends the message only to the sender (the client that just connected) by default.
from flask_socketio import SocketIO socketio = SocketIO(app) # Assume 3 clients are connected socketio.emit('update', {'data': 'refresh'}, broadcast=True)
Setting broadcast=True sends the message to all connected clients, so all 3 clients receive it.
@socketio.on('join') def on_join(data): room = data['room'] join_room(room) @socketio.on('send') def on_send(data): room = data['room'] socketio.emit('message', {'msg': data['msg']}, room=room)
If join_room is not imported from flask_socketio or not called correctly, clients won't join the room, so emitting to that room sends to no one.
The correct parameter to specify a room in Flask-SocketIO emit is 'room'. Using 'rooms' or 'to' is invalid and causes errors.
socketio.emit('notify', {'msg': 'update'}, broadcast=True, include_self=False)
Setting broadcast=True sends to all clients, and include_self=False excludes the sender from receiving the message.
