0
0
Raspberry Piprogramming~20 mins

WebSocket for live updates in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
WebSocket Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
WebSocket server message broadcast output
What will be the output on the client console when the server broadcasts a message to all connected clients?
Raspberry Pi
import asyncio
import websockets

connected = set()

async def handler(websocket):
    connected.add(websocket)
    try:
        async for message in websocket:
            for conn in connected:
                if conn != websocket:
                    await conn.send(f"Broadcast: {message}")
    finally:
        connected.remove(websocket)

async def main():
    async with websockets.serve(handler, "localhost", 8765):
        await asyncio.Future()  # run forever

# Client code snippet:
# async def client():
#     async with websockets.connect("ws://localhost:8765") as ws:
#         await ws.send("Hello")
#         response = await ws.recv()
#         print(response)

# Assume two clients connect and one sends "Hello"
ANo output
BBroadcast: Hello
CError: Cannot send message to self
DHello
Attempts:
2 left
💡 Hint
Think about how the server sends messages to all clients except the sender.
🧠 Conceptual
intermediate
1:00remaining
WebSocket connection states
Which WebSocket connection state indicates that the connection is open and ready to communicate?
ACONNECTING
BCLOSING
CCLOSED
DOPEN
Attempts:
2 left
💡 Hint
Think about when you can send and receive messages.
🔧 Debug
advanced
2:00remaining
Identify the error in WebSocket server code
What error will this WebSocket server code raise when run?
Raspberry Pi
import asyncio
import websockets

async def handler(websocket):
    async for message in websocket:
        await websocket.send(message.upper())

async def main():
    server = await websockets.serve(handler, 'localhost', 8765)
    await server

asyncio.run(main())
ATypeError: 'WebSocketServer' object is not awaitable
BRuntimeError: Event loop is closed
CSyntaxError: invalid syntax
DNo error, runs correctly
Attempts:
2 left
💡 Hint
Check how the server object is awaited.
📝 Syntax
advanced
1:30remaining
Correct WebSocket client connection syntax
Which option shows the correct way to connect to a WebSocket server and receive a message in Python?
A
with websockets.connect('ws://localhost:8765') as ws:
    message = await ws.recv()
    print(message)
B
async with websockets.connect('ws://localhost:8765') as ws:
    message = ws.recv()
    print(message)
C
async with websockets.connect('ws://localhost:8765') as ws:
    message = await ws.recv()
    print(message)
D
with websockets.connect('ws://localhost:8765') as ws:
    message = ws.recv()
    print(message)
Attempts:
2 left
💡 Hint
Remember that 'recv' is an async function and needs 'await' inside an async context.
🚀 Application
expert
2:30remaining
Number of messages received in a WebSocket client
Given this client code connecting to a server that sends a message every second for 5 seconds, how many messages will the client receive before closing?
Raspberry Pi
import asyncio
import websockets

async def client():
    async with websockets.connect('ws://localhost:8765') as ws:
        count = 0
        try:
            while True:
                msg = await asyncio.wait_for(ws.recv(), timeout=6)
                count += 1
        except asyncio.TimeoutError:
            pass
        print(count)

asyncio.run(client())
A5
B6
C0
DRaises TimeoutError
Attempts:
2 left
💡 Hint
The server sends 5 messages, one each second, and client waits up to 6 seconds for each.