What if your app could talk to the server instantly, like a live conversation?
Why WebSocket protocol concept in Node.js? - Purpose & Use Cases
Imagine building a chat app where users must refresh the page to see new messages.
Every time you want to get new data, you send a request and wait for a response.
This request-response way is slow and wastes resources because the server can't send updates on its own.
Users see delays and the app feels unresponsive.
WebSocket creates a constant open connection between client and server.
This lets both sides send messages instantly without waiting for requests.
setInterval(() => fetch('/messages').then(response => response.json()).then(data => console.log(data)), 5000);
const ws = new WebSocket('ws://server'); ws.onmessage = e => console.log(e.data);Real-time, two-way communication that feels instant and smooth for users.
Live sports scores updating on your screen without refreshing the page.
Manual polling is slow and inefficient.
WebSocket keeps a live connection open for instant updates.
This improves user experience with real-time data.
Practice
Solution
Step 1: Understand WebSocket communication
WebSocket allows a persistent connection where both client and server can send messages anytime.Step 2: Compare with other options
HTTP requests are one-way and short-lived, static files serving and data storage are unrelated to WebSocket's main role.Final Answer:
To create a live, two-way communication channel between client and server -> Option BQuick Check:
WebSocket = two-way live connection [OK]
- Confusing WebSocket with HTTP request-response
- Thinking WebSocket serves static files
- Assuming WebSocket stores data permanently
Solution
Step 1: Recall 'ws' library syntax
The 'ws' library creates a server with new WebSocket.Server and a config object with port.Step 2: Check each option
Only const ws = new WebSocket.Server({ port: 8080 }); uses correct constructor and port option. Others use invalid methods or constructors.Final Answer:
const ws = new WebSocket.Server({ port: 8080 }); -> Option CQuick Check:
WebSocket.Server + port config = correct [OK]
- Using WebSocket constructor instead of WebSocket.Server
- Calling non-existent methods like createServer or listen
- Passing port as a direct argument instead of in an object
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', message => {
console.log(`Received: ${message}`);
ws.send('pong');
});
});Solution
Step 1: Analyze message event handler
When the server receives a message, it logs 'Received: ' plus the message content.Step 2: Identify logged output
Client sends 'hello', so console logs 'Received: hello'. The server sends back 'pong' but that is not logged.Final Answer:
Received: hello -> Option AQuick Check:
Server logs received message text [OK]
- Confusing sent message with logged message
- Thinking server logs the reply it sends
- Mixing up client and server console outputs
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', (msg) => {
ws.send(msg.toUpperCase);
});
});Solution
Step 1: Check usage of toUpperCase
toUpperCase is a function and must be called with parentheses to get the uppercase string.Step 2: Verify other parts
WebSocket.Server is correct, 'message' event is correct, port can be a number.Final Answer:
msg.toUpperCase should be called as a function: msg.toUpperCase() -> Option DQuick Check:
Call string methods with () [OK]
- Forgetting parentheses on string methods
- Using wrong event names like 'onMessage'
- Confusing WebSocket server creation syntax
Solution
Step 1: Understand broadcasting logic
Broadcast means sending message to all clients except the sender, checking if client connection is open.Step 2: Analyze each option
wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); }); loops over all clients, skips sender, checks readyState, and sends message correctly. Others either send only to sender, call invalid methods, or listen on wrong event.Final Answer:
Option A code snippet correctly broadcasts to all except sender -> Option AQuick Check:
Broadcast = send to all except sender with readyState check [OK]
- Sending message only back to sender
- Calling send on wss object instead of clients
- Not checking client.readyState before sending
Ready to prove it?
Pass the test and this pattern moves unknown
