Bird
Raised Fist0
Flaskframework~20 mins

WebSocket events handling in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a client connects?

Consider this Flask-SocketIO server code snippet. What message will the server send to the client immediately after connection?

Flask
from flask_socketio import SocketIO, emit

socketio = SocketIO()

@socketio.on('connect')
def handle_connect():
    emit('welcome', {'msg': 'Hello, client!'})
AThe client receives no message until it sends a message first
BThe client receives an event 'connect' with data {'msg': 'Hello, client!'}
CThe client receives an event 'welcome' with data {'msg': 'Hello, client!'}
DThe server raises an error because emit is not allowed in connect event
Attempts:
2 left
💡 Hint

Remember that emit sends events to the client. The event name is the first argument.

❓ state_output
intermediate
2:00remaining
What is the value of 'count' after three 'increment' events?

Given this Flask-SocketIO server code, what will be the value of count after the client sends the 'increment' event three times?

Flask
from flask_socketio import SocketIO, emit

socketio = SocketIO()
count = 0

@socketio.on('increment')
def handle_increment():
    global count
    count += 1
    emit('count_updated', {'count': count})
A1
B3
C0
DRaises UnboundLocalError
Attempts:
2 left
💡 Hint

Check how the count variable is updated and the use of global.

📝 Syntax
advanced
2:00remaining
Which option causes a SyntaxError in Flask-SocketIO event handler?

Identify which code snippet will cause a syntax error when defining a Flask-SocketIO event handler.

A
@socketio.on('message')
def handle_message()
    print('Message received')
B
@socketio.on('message')
def handle_message():
    print('Message received')
C
@socketio.on('message')
def handle_message():
    emit('response', {'data': 'ok'})
D
@socketio.on('message')
async def handle_message():
    await some_async_func()
Attempts:
2 left
💡 Hint

Look for missing punctuation or incorrect function definitions.

🔧 Debug
advanced
2:00remaining
Why does the server not respond to 'chat' events?

Given this Flask-SocketIO server code, the client sends 'chat' events but receives no response. What is the likely cause?

Flask
from flask_socketio import SocketIO, emit

socketio = SocketIO()

@socketio.on('message')
def handle_message(data):
    emit('response', {'msg': data['msg']})
AThe function handle_message lacks the global keyword for data
BThe emit call is missing the broadcast=True argument
CThe server must use @socketio.event decorator instead of @socketio.on
DThe event handler listens for 'message' but client sends 'chat', so no handler is triggered
Attempts:
2 left
💡 Hint

Check if the event names match between client and server.

🧠 Conceptual
expert
2:00remaining
What happens if you emit an event outside a SocketIO event context?

In Flask-SocketIO, what is the behavior when you call emit('update', data) outside of any event handler or request context?

AEmit raises a RuntimeError because there is no active SocketIO context
BEmit sends the event to all connected clients automatically
CEmit queues the event and sends it when a client connects
DEmit silently does nothing without error
Attempts:
2 left
💡 Hint

Think about how Flask-SocketIO manages context for emitting events.

Practice

(1/5)
1. What does the decorator @socketio.on('message') do in a Flask app using WebSocket?
easy
A. It closes the WebSocket connection.
B. It sends a WebSocket message to all connected clients.
C. It listens for incoming WebSocket messages with the event name 'message'.
D. It initializes the Flask app.

Solution

  1. Step 1: Understand the decorator role

    The @socketio.on('message') decorator registers a function to handle incoming WebSocket events named 'message'.
  2. Step 2: Differentiate from other actions

    Sending messages or closing connections are done by other functions, not by this decorator.
  3. Final Answer:

    It listens for incoming WebSocket messages with the event name 'message'. -> Option C
  4. Quick Check:

    Decorator for event handling = C [OK]
Hint: Remember: @socketio.on listens, send() sends [OK]
Common Mistakes:
  • Confusing event handler with sending messages
  • Thinking it closes connections
  • Assuming it initializes the app
2. Which of the following is the correct syntax to send a message back to the client inside a WebSocket event handler in Flask-SocketIO?
easy
A. socketio.send('Hello client!')
B. send('Hello client!')
C. emit('Hello client!')
D. socket.emit('Hello client!')

Solution

  1. Step 1: Identify the correct function call

    In Flask-SocketIO, use the imported send() function inside handlers to reply to the sender client.
  2. Step 2: Check syntax correctness

    A: 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.
  3. Final Answer:

    send('Hello client!') -> Option B
  4. Quick Check:

    Use send() to reply to sender [OK]
Hint: send() replies to sender, socketio.send() to all [OK]
Common Mistakes:
  • Using socketio.send() which sends to all clients
  • Malformed emit() call without data
  • Using undefined socket object
3. Given this Flask-SocketIO event handler code:
@socketio.on('chat')
def handle_chat(msg):
    print('Received:', msg)
    send('Echo: ' + msg)

What will be printed and sent if the client sends the message 'Hi'?
medium
A. Causes a runtime error because send() needs an event name.
B. Prints 'Echo: Hi' and sends 'Received: Hi' back to the client.
C. Prints nothing and sends 'Hi' back to the client.
D. Prints 'Received: Hi' and sends 'Echo: Hi' back to the client.

Solution

  1. Step 1: Analyze the print statement

    The function prints 'Received: ' plus the message, so it prints 'Received: Hi'.
  2. Step 2: Analyze the send() call

    The send() function sends the string 'Echo: ' plus the message back to the client, so it sends 'Echo: Hi'.
  3. Final Answer:

    Prints 'Received: Hi' and sends 'Echo: Hi' back to the client. -> Option D
  4. Quick Check:

    Print then send echo message = D [OK]
Hint: Print shows received, send echoes message [OK]
Common Mistakes:
  • Mixing print output with sent message
  • Assuming send() needs event name
  • Confusing order of print and send
4. Identify the error in this Flask-SocketIO event handler:
@socketio.on('update')
def handle_update():
    data = request.json
    send(data)
medium
A. Using request.json inside WebSocket handler causes an error.
B. Missing event name in @socketio.on decorator.
C. send() cannot send JSON data.
D. Function must have a parameter to receive message data.

Solution

  1. Step 1: Understand request context in WebSocket

    WebSocket handlers do not have HTTP request context, so request.json is not available and causes an error.
  2. Step 2: Check other parts

    The decorator has event name, send() can send JSON, and function can have zero parameters if no message expected.
  3. Final Answer:

    Using request.json inside WebSocket handler causes an error. -> Option A
  4. Quick Check:

    request.json not available in WebSocket handlers [OK]
Hint: Don't use request.json in WebSocket handlers [OK]
Common Mistakes:
  • Assuming HTTP request context exists in WebSocket
  • Thinking send() can't send JSON
  • Believing function must have parameters always
5. You want to broadcast a message to all connected clients except the sender in Flask-SocketIO. Which code snippet correctly does this inside an event handler?
hard
A. emit('broadcast', data, broadcast=true, include_self=false)
B. send(data, broadcast=true, include_self=true)
C. emit('broadcast', data, broadcast=true, include_self=true)
D. send(data, include_self=false)

Solution

  1. Step 1: Understand broadcasting options

    To send to all except sender, use emit() with broadcast=true and include_self=false.
  2. Step 2: Check each option

    B: 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.
  3. Final Answer:

    emit('broadcast', data, broadcast=true, include_self=false) -> Option A
  4. Quick Check:

    Broadcast exclude sender = emit with include_self=false [OK]
Hint: Use emit with broadcast=true and include_self=false [OK]
Common Mistakes:
  • Using send() incorrectly for targeted broadcast
  • Setting include_self=true which includes sender
  • Missing broadcast=true flag
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard