Bird
Raised Fist0
Raspberry Piprogramming~20 mins

WebSocket for live updates in Raspberry Pi - 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!
❓ 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.

Practice

(1/5)
1. What is the main advantage of using WebSocket on a Raspberry Pi for live updates?
easy
A. It keeps a connection open for instant two-way data flow.
B. It sends data only once when the page loads.
C. It requires no network connection to work.
D. It stores data locally on the Raspberry Pi.

Solution

  1. Step 1: Understand WebSocket connection behavior

    WebSocket keeps a connection open between the Raspberry Pi and the web page, allowing data to flow instantly both ways.
  2. Step 2: Compare options with WebSocket features

    Options A, B, and C do not describe WebSocket's live, continuous connection feature.
  3. Final Answer:

    It keeps a connection open for instant two-way data flow. -> Option A
  4. Quick Check:

    WebSocket = open two-way connection [OK]
Hint: Remember: WebSocket keeps connection open for live updates [OK]
Common Mistakes:
  • Thinking WebSocket sends data only once
  • Confusing WebSocket with HTTP request-response
  • Assuming WebSocket works offline
2. Which of the following is the correct way to create a WebSocket client connection in JavaScript on a Raspberry Pi web page?
easy
A. const socket = new Socket('ws://localhost:8080');
B. const socket = WebSocket.connect('http://localhost:8080');
C. const socket = WebSocket('https://localhost:8080');
D. const socket = new WebSocket('ws://localhost:8080');

Solution

  1. Step 1: Recall correct WebSocket syntax in JavaScript

    The correct syntax to create a WebSocket client is using the WebSocket constructor with the URL starting with 'ws://' or 'wss://'.
  2. Step 2: Check each option's syntax

    const socket = new WebSocket('ws://localhost:8080'); uses 'new WebSocket' with 'ws://' which is correct. Options A, B, and D use incorrect methods or protocols.
  3. Final Answer:

    const socket = new WebSocket('ws://localhost:8080'); -> Option D
  4. Quick Check:

    WebSocket client = new WebSocket('ws://...') [OK]
Hint: Use 'new WebSocket("ws://...")' to create connection [OK]
Common Mistakes:
  • Using 'http://' instead of 'ws://'
  • Calling WebSocket as a function without 'new'
  • Using undefined methods like WebSocket.connect
3. Given this Python code running on a Raspberry Pi using the 'websockets' library, what will be printed when a client connects and sends 'Hello'?
import asyncio
import websockets

async def handler(websocket):
    message = await websocket.recv()
    print(f'Received: {message}')

async def main():
    async with websockets.serve(handler, 'localhost', 8765):
        await asyncio.Future()

asyncio.run(main())
medium
A. Received: Hello
B. Received: websocket
C. Error: No client connected
D. Received: None

Solution

  1. Step 1: Understand the handler function

    The handler waits to receive a message from the client and then prints it with 'Received: ' prefix.
  2. Step 2: Analyze what happens when client sends 'Hello'

    The message 'Hello' is received and printed as 'Received: Hello'.
  3. Final Answer:

    Received: Hello -> Option A
  4. Quick Check:

    Received message = 'Hello' [OK]
Hint: Handler prints whatever client sends prefixed by 'Received:' [OK]
Common Mistakes:
  • Assuming it prints 'websocket' instead of message
  • Expecting an error without client connection
  • Thinking it prints None if message missing
4. Identify the error in this Raspberry Pi WebSocket server code snippet:
import asyncio
import websockets

async def handler(websocket):
    while True:
        message = websocket.recv()
        print(message)

async def main():
    async with websockets.serve(handler, 'localhost', 8765):
        await asyncio.Future()

asyncio.run(main())
medium
A. The server address 'localhost' is invalid.
B. The while loop should be outside the handler function.
C. Missing 'await' before websocket.recv() call.
D. The 'asyncio.run(main())' should be 'asyncio.start(main())'.

Solution

  1. Step 1: Check asynchronous calls in handler

    The 'websocket.recv()' is a coroutine and must be awaited to get the message.
  2. Step 2: Verify other parts of the code

    Address 'localhost' is valid, the loop inside handler is correct for continuous receiving, and 'asyncio.run' is the proper way to start.
  3. Final Answer:

    Missing 'await' before websocket.recv() call. -> Option C
  4. Quick Check:

    Await async calls like websocket.recv() [OK]
Hint: Always await async functions like websocket.recv() [OK]
Common Mistakes:
  • Forgetting 'await' on async calls
  • Misplacing the while loop
  • Using wrong asyncio start function
5. You want your Raspberry Pi to send live temperature updates to a web page using WebSocket. Which approach best ensures the web page updates instantly when the sensor value changes?
hard
A. Open a new WebSocket connection every time the temperature changes.
B. Open a WebSocket connection once, then send new temperature data whenever it changes.
C. Send temperature data only when the web page reloads.
D. Use HTTP GET requests repeatedly to fetch temperature data.

Solution

  1. Step 1: Understand WebSocket usage for live updates

    WebSocket keeps a connection open, so sending data only when it changes over the same connection is efficient and instant.
  2. Step 2: Evaluate other options

    Opening new connections repeatedly (B) wastes resources. Sending data only on reload (C) or using HTTP polling (D) is slower and less real-time.
  3. Final Answer:

    Open a WebSocket connection once, then send new temperature data whenever it changes. -> Option B
  4. Quick Check:

    One open connection + send updates = instant live data [OK]
Hint: Keep one connection open; send updates as they happen [OK]
Common Mistakes:
  • Opening multiple connections unnecessarily
  • Relying on page reloads for updates
  • Using HTTP polling instead of WebSocket
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