Which statement best describes why WebSocket can be a good alternative to Server-Sent Events (SSE) in Flask applications?
Think about the direction of data flow in WebSocket compared to SSE.
WebSocket supports full-duplex communication, meaning both client and server can send messages independently. SSE only allows server to send updates to the client.
Given a Flask app using Flask-SocketIO, what will happen when the server emits a message to a connected client?
from flask import Flask from flask_socketio import SocketIO, emit app = Flask(__name__) socketio = SocketIO(app) @socketio.on('connect') def handle_connect(): emit('message', {'data': 'Welcome!'})
Consider what happens when a client connects to a WebSocket server.
When a client connects, the server can immediately send messages using emit. The client does not need to request data first.
Which option shows the correct syntax for a Flask-SocketIO event handler that listens for a 'chat message' event and sends a response?
Check the Flask-SocketIO documentation for the correct decorator to listen for events.
The correct decorator to listen for a named event is @socketio.on('event_name'). Other decorators or methods are invalid.
A developer uses Flask-SocketIO but clients never receive messages. The server code is:
from flask import Flask
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@socketio.on('connect')
def on_connect():
emit('message', {'data': 'Hello'})
if __name__ == '__main__':
app.run()What is the main reason clients do not receive messages?
Consider how Flask-SocketIO requires the server to be started.
Flask-SocketIO requires using socketio.run(app) to enable WebSocket support. Using app.run() starts a plain Flask server without WebSocket.
Consider a Flask-SocketIO server that keeps a counter of connected clients and broadcasts it on each connection and disconnection:
from flask import Flask
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
connected_clients = 0
@socketio.on('connect')
def on_connect():
global connected_clients
connected_clients += 1
socketio.emit('clients', {'count': connected_clients})
@socketio.on('disconnect')
def on_disconnect():
global connected_clients
connected_clients -= 1
socketio.emit('clients', {'count': connected_clients})If three clients connect one after another, then one disconnects, what is the sequence of 'count' values broadcasted?
Track the value of connected_clients after each event.
Each connect increments the counter and broadcasts it: 1, then 2, then 3. One disconnect decrements it to 2 and broadcasts again.