Performance: WebSocket events handling
This affects the responsiveness and smoothness of real-time updates on the page by controlling how WebSocket events are processed and rendered.
from flask_socketio import SocketIO, emit import threading socketio = SocketIO(app) def background_task(data): result = complex_calculation(data) socketio.emit('response', result) @socketio.on('message') def handle_message(data): threading.Thread(target=background_task, args=(data,)).start()
from flask_socketio import SocketIO, emit socketio = SocketIO(app) @socketio.on('message') def handle_message(data): # Heavy processing on main thread result = complex_calculation(data) emit('response', result)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking heavy processing in event handler | Multiple DOM updates per event | Multiple reflows if DOM updated repeatedly | High paint cost due to frequent layout changes | [X] Bad |
| Background thread processing with batched DOM updates | Batched DOM updates | Single reflow per batch | Lower paint cost due to fewer layout changes | [OK] Good |
@socketio.on('message') do in a Flask app using WebSocket?@socketio.on('message') decorator registers a function to handle incoming WebSocket events named 'message'.send() function inside handlers to reply to the sender client.send('Hello client!') correctly sends to sender. B: socketio.send() sends to all clients. C: emit('Hello client!') uses message as event name without data. D: socket undefined.@socketio.on('chat')
def handle_chat(msg):
print('Received:', msg)
send('Echo: ' + msg)@socketio.on('update')
def handle_update():
data = request.json
send(data)request.json is not available and causes an error.emit() with broadcast=true and include_self=false.send(data, broadcast=true, include_self=true) includes sender. C: emit('broadcast', data, broadcast=true, include_self=true) includes sender. D: send(data, include_self=false) lacks broadcast flag. A correctly excludes sender.Pass the test and this pattern moves unknown