WebSocket events handling lets your Flask app talk to users instantly. It helps send and receive messages without waiting for page reloads.
0
0
WebSocket events handling in Flask
Introduction
You want a chat app where messages appear right away.
You need live updates on a dashboard without refreshing.
You want to notify users instantly about new events.
You build a game that needs real-time player moves.
You want to track live data like stock prices or sensors.
Syntax
Flask
from flask import Flask from flask_socketio import SocketIO, send, emit app = Flask(__name__) socketio = SocketIO(app) @socketio.on('event_name') def handle_event(data): # code to handle event pass if __name__ == '__main__': socketio.run(app)
Use @socketio.on('event_name') to listen for WebSocket events.
Inside the handler, use send() or emit() to reply.
Examples
This listens for a 'message' event and sends back a confirmation.
Flask
@socketio.on('message') def handle_message(msg): send(f'Received: {msg}')
This listens for a 'json' event and emits a 'response' event with data.
Flask
@socketio.on('json') def handle_json(json_data): emit('response', {'data': 'Got your JSON!'})
This runs when a client connects to the WebSocket.
Flask
@socketio.on('connect') def on_connect(): print('Client connected')
Sample Program
This Flask app listens for 'message' events from clients. When a message arrives, it prints it on the server and sends a reply back to the client.
Flask
from flask import Flask from flask_socketio import SocketIO, send app = Flask(__name__) socketio = SocketIO(app) @socketio.on('message') def handle_message(msg): print(f'Received message: {msg}') send(f'Server says: {msg}') if __name__ == '__main__': socketio.run(app, debug=True)
OutputSuccess
Important Notes
Remember to run your Flask app with socketio.run(app) instead of app.run().
Use send() for simple messages and emit() for custom events.
WebSocket events let your app be interactive and real-time without page reloads.
Summary
WebSocket events let Flask apps send and receive messages instantly.
Use @socketio.on('event') to handle events and send() or emit() to reply.
This is great for chat, live updates, notifications, and games.