WebSocket lets your app talk to a server in real-time. It keeps the connection open so messages can flow back and forth instantly.
WebSocket protocol concept in Node.js
const ws = new WebSocket('ws://example.com/socket'); ws.onopen = () => { ws.send('Hello Server!'); }; ws.onmessage = (event) => { console.log('Message from server:', event.data); }; ws.onclose = () => { console.log('Connection closed'); };
Use ws:// for unencrypted and wss:// for secure connections.
Events like onopen, onmessage, and onclose handle connection states.
wss:// and send a message when connected.const ws = new WebSocket('wss://example.com/socket'); ws.onopen = () => { ws.send('Hi!'); };
ws.onmessage = (event) => {
console.log(`Received: ${event.data}`);
};ws.onclose = () => {
console.log('Socket closed');
};This Node.js program creates a WebSocket server on port 8080. When a client connects, it logs a message. It listens for messages from the client, logs them, and sends back the same message prefixed with 'Echo:'. It also logs when the client disconnects.
import WebSocket from 'ws'; const server = new WebSocket.Server({ port: 8080 }); server.on('connection', (socket) => { console.log('Client connected'); socket.on('message', (message) => { console.log('Received:', message.toString()); socket.send(`Echo: ${message}`); }); socket.on('close', () => { console.log('Client disconnected'); }); }); console.log('WebSocket server running on ws://localhost:8080');
WebSocket keeps the connection open, unlike HTTP which closes after each request.
Use secure WebSocket (wss://) for sensitive data to protect privacy.
WebSocket works well for apps needing instant updates without refreshing.
WebSocket creates a live, two-way connection between client and server.
It is great for real-time apps like chat, games, and live feeds.
Use event handlers to send and receive messages easily.
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
