The server listens for 'connection' events, then for each connection listens for 'message' events.
Step 2: Analyze message event handler
When a message arrives, it logs 'Received: ' plus the message content.
Final Answer:
Received: Hello -> Option D
Quick Check:
Message event logs 'Received: message' [OK]
Hint: Message event logs 'Received: ' plus message text [OK]
Common Mistakes:
Expecting raw 'message' string without prefix
Confusing event names or handlers
Thinking ws.on is undefined
4. Identify the error in this WebSocket server setup code:
const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = http.createServer();
const wss = new WebSocket.Server({ server });
server.listen(3000);
medium
A. WebSocket.Server should not receive server option
B. http module is not imported
C. express() should be passed to WebSocket.Server
D. server.listen should be called before creating WebSocket.Server
Solution
Step 1: Check module imports
The code uses http.createServer() but does not import the 'http' module, causing a ReferenceError.
Step 2: Verify server creation and usage
http.createServer() requires the http module; without import, server is undefined.
Final Answer:
http module is not imported -> Option B
Quick Check:
Missing http import causes error [OK]
Hint: Always import http before using http.createServer() [OK]
Common Mistakes:
Forgetting to import http module
Passing express app directly to WebSocket.Server
Calling listen before server creation
5. You want to broadcast a message to all connected WebSocket clients when one client sends a message. Which code snippet correctly implements this inside the 'connection' event handler?
wss.on('connection', ws => {
ws.on('message', message => {
// Broadcast message to all clients
???
});
});
hard
A. ws.clients.forEach(client => client.send(message));
B. wss.broadcast(message);
C. wss.clients.forEach(client => { if(client.readyState === WebSocket.OPEN) client.send(message); });
D. server.clients.forEach(client => client.send(message));
Solution
Step 1: Identify how to access all clients
The WebSocket.Server instance 'wss' has a 'clients' set containing all connected clients.
Step 2: Filter clients by open connection and send message
Only clients with readyState === WebSocket.OPEN can receive messages safely.