Bird
0
0

What is wrong with this JavaScript WebSocket client code on a Raspberry Pi?

medium📝 Debug Q7 of 15
Raspberry Pi - Web Server and API
What is wrong with this JavaScript WebSocket client code on a Raspberry Pi? const socket = new WebSocket('ws://localhost:9000'); socket.send('Hello'); socket.onmessage = (msg) => console.log(msg.data);
AUsing console.log incorrectly
BMissing event listener for errors
CIncorrect WebSocket URL
DSending message before connection is open
Step-by-Step Solution
Solution:
  1. Step 1: Understand WebSocket connection timing

    Messages must be sent only after the connection is open.
  2. Step 2: Identify the error

    Code sends 'Hello' immediately, before 'onopen' event, causing failure.
  3. Final Answer:

    Sending message before connection is open -> Option D
  4. Quick Check:

    Send only after onopen event [OK]
Quick Trick: Send messages only after onopen event fires [OK]
Common Mistakes:
MISTAKES
  • Sending messages immediately after creating socket
  • Ignoring connection open event
  • Assuming send queues messages automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes