WebSocket for live updates in Raspberry Pi - Time & Space Complexity
When using WebSocket for live updates, it is important to understand how the program's work grows as more messages arrive.
We want to know how the time to handle updates changes when the number of messages increases.
Analyze the time complexity of the following code snippet.
// Pseudocode for WebSocket message handling
websocket.on('message', (msg) => {
processMessage(msg); // handle one message
});
function processMessage(msg) {
updateDisplay(msg); // update UI with new data
}
This code listens for messages from a WebSocket and updates the display each time a message arrives.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Handling each incoming message one by one.
- How many times: Once per message received from the WebSocket connection.
Each new message causes one update operation. So, if more messages come, the total work grows directly with the number of messages.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 messages | 10 update calls |
| 100 messages | 100 update calls |
| 1000 messages | 1000 update calls |
Pattern observation: The work grows in a straight line as messages increase.
Time Complexity: O(n)
This means the time to handle messages grows directly with the number of messages received.
[X] Wrong: "Handling one message takes the same total time no matter how many messages come later."
[OK] Correct: Each message requires its own processing time, so more messages mean more total work.
Understanding how live updates scale helps you explain how your code will behave with many users or messages, a useful skill in real projects.
What if we batch multiple messages together before updating the display? How would the time complexity change?
Practice
Solution
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.Step 2: Compare options with WebSocket features
Options A, B, and C do not describe WebSocket's live, continuous connection feature.Final Answer:
It keeps a connection open for instant two-way data flow. -> Option AQuick Check:
WebSocket = open two-way connection [OK]
- Thinking WebSocket sends data only once
- Confusing WebSocket with HTTP request-response
- Assuming WebSocket works offline
Solution
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://'.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.Final Answer:
const socket = new WebSocket('ws://localhost:8080'); -> Option DQuick Check:
WebSocket client = new WebSocket('ws://...') [OK]
- Using 'http://' instead of 'ws://'
- Calling WebSocket as a function without 'new'
- Using undefined methods like WebSocket.connect
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())Solution
Step 1: Understand the handler function
The handler waits to receive a message from the client and then prints it with 'Received: ' prefix.Step 2: Analyze what happens when client sends 'Hello'
The message 'Hello' is received and printed as 'Received: Hello'.Final Answer:
Received: Hello -> Option AQuick Check:
Received message = 'Hello' [OK]
- Assuming it prints 'websocket' instead of message
- Expecting an error without client connection
- Thinking it prints None if message missing
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())Solution
Step 1: Check asynchronous calls in handler
The 'websocket.recv()' is a coroutine and must be awaited to get the message.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.Final Answer:
Missing 'await' before websocket.recv() call. -> Option CQuick Check:
Await async calls like websocket.recv() [OK]
- Forgetting 'await' on async calls
- Misplacing the while loop
- Using wrong asyncio start function
Solution
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.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.Final Answer:
Open a WebSocket connection once, then send new temperature data whenever it changes. -> Option BQuick Check:
One open connection + send updates = instant live data [OK]
- Opening multiple connections unnecessarily
- Relying on page reloads for updates
- Using HTTP polling instead of WebSocket
Ready to prove it?
Pass the test and this pattern moves unknown
