Bird
Raised Fist0
Node.jsframework~10 mins

WebSocket protocol concept in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - WebSocket protocol concept
Client sends HTTP Upgrade request
↓
Server receives Upgrade request
↓
Server sends HTTP 101 Switching Protocols
↓
WebSocket connection established
↓
Bidirectional message exchange
↓
Connection close initiated by client or server
↓
Connection closed
This flow shows how a WebSocket connection starts with an HTTP upgrade, then allows two-way messages until closed.
Execution Sample
Node.js
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => ws.send('Hello'));
ws.on('message', msg => console.log(msg));
This code connects to a WebSocket server, sends 'Hello' when open, and logs incoming messages.
Execution Table
StepActionMessage SentMessage ReceivedConnection State
1Client sends HTTP Upgrade requestUpgrade requestConnecting
2Server receives Upgrade requestConnecting
3Server sends HTTP 101 Switching Protocols101 Switching ProtocolsUpgrading
4Connection establishedOpen
5Client sends 'Hello'HelloOpen
6Server sends 'Welcome'WelcomeOpen
7Client sends 'How are you?'How are you?Open
8Server sends 'Good, thanks!'Good, thanks!Open
9Client initiates closeClose frameClosing
10Server acknowledges closeClose frameClosed
💡 Connection closes after client and server exchange close frames.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6After Step 9Final
Connection StateConnectingOpenOpenOpenClosingClosed
Last Message SentNoneNoneHelloHelloClose frameClose frame
Last Message ReceivedNoneNoneNoneWelcomeGood, thanks!Close frame
Key Moments - 3 Insights
Why does the connection start as HTTP before switching to WebSocket?
Because WebSocket begins as a normal HTTP request with an Upgrade header (see Step 1 and 3 in execution_table), allowing servers and proxies to handle it like HTTP before switching protocols.
What does '101 Switching Protocols' mean in the process?
It is the server's response (Step 3) telling the client it agrees to switch from HTTP to WebSocket, enabling the full-duplex communication.
How do client and server know when to close the connection?
They send special 'Close frame' messages (Steps 9 and 10) signaling intent to close, ensuring both sides agree before closing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the connection state after Step 4?
AOpen
BConnecting
CClosing
DClosed
💡 Hint
Check the 'Connection State' column at Step 4 in execution_table.
At which step does the client send the first message after connection is open?
AStep 3
BStep 7
CStep 5
DStep 9
💡 Hint
Look for 'Client sends' actions in the 'Action' column in execution_table.
If the server never sends '101 Switching Protocols', what happens to the connection?
AConnection becomes Open anyway
BConnection stays in Connecting state
CConnection immediately closes
DClient sends Close frame
💡 Hint
Refer to Step 3 and the importance of the 101 response in execution_table.
Concept Snapshot
WebSocket starts as an HTTP request with an Upgrade header.
Server responds with 101 Switching Protocols to agree.
Connection becomes full-duplex for bidirectional messages.
Messages are sent as frames over the open connection.
Close frames signal connection termination by either side.
Full Transcript
The WebSocket protocol begins with the client sending an HTTP request asking to upgrade the connection. The server responds with a 101 Switching Protocols status to confirm the upgrade. Once established, the connection is open for two-way communication where client and server can send messages independently. When either side wants to end the connection, they send a close frame to signal termination. This process ensures a smooth transition from HTTP to a persistent, bidirectional WebSocket connection.

Practice

(1/5)
1. What is the main purpose of the WebSocket protocol in Node.js applications?
easy
A. To send HTTP requests from client to server
B. To create a live, two-way communication channel between client and server
C. To serve static files like HTML and CSS
D. To store data permanently on the server

Solution

  1. Step 1: Understand WebSocket communication

    WebSocket allows a persistent connection where both client and server can send messages anytime.
  2. 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.
  3. Final Answer:

    To create a live, two-way communication channel between client and server -> Option B
  4. Quick Check:

    WebSocket = two-way live connection [OK]
Hint: WebSocket means live two-way chat between client and server [OK]
Common Mistakes:
  • Confusing WebSocket with HTTP request-response
  • Thinking WebSocket serves static files
  • Assuming WebSocket stores data permanently
2. Which of the following is the correct way to create a WebSocket server using the 'ws' library in Node.js?
easy
A. const ws = new WebSocket(8080);
B. const ws = WebSocket.createServer(8080);
C. const ws = new WebSocket.Server({ port: 8080 });
D. const ws = WebSocket.listen(8080);

Solution

  1. Step 1: Recall 'ws' library syntax

    The 'ws' library creates a server with new WebSocket.Server and a config object with port.
  2. 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.
  3. Final Answer:

    const ws = new WebSocket.Server({ port: 8080 }); -> Option C
  4. Quick Check:

    WebSocket.Server + port config = correct [OK]
Hint: Use new WebSocket.Server({ port }) to create server [OK]
Common Mistakes:
  • 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
3. Given this Node.js WebSocket server code snippet, what will be logged when a client sends the message 'hello'?
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');
  });
});
medium
A. Received: hello
B. pong
C. Received: pong
D. hello

Solution

  1. Step 1: Analyze message event handler

    When the server receives a message, it logs 'Received: ' plus the message content.
  2. Step 2: Identify logged output

    Client sends 'hello', so console logs 'Received: hello'. The server sends back 'pong' but that is not logged.
  3. Final Answer:

    Received: hello -> Option A
  4. Quick Check:

    Server logs received message text [OK]
Hint: Server logs 'Received: message' on message event [OK]
Common Mistakes:
  • Confusing sent message with logged message
  • Thinking server logs the reply it sends
  • Mixing up client and server console outputs
4. Identify the error in this WebSocket server code snippet:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
  ws.on('message', (msg) => {
    ws.send(msg.toUpperCase);
  });
});
medium
A. The port number must be a string, not a number
B. WebSocket.Server should be WebSocket.createServer
C. The 'message' event handler should be 'onMessage'
D. msg.toUpperCase should be called as a function: msg.toUpperCase()

Solution

  1. Step 1: Check usage of toUpperCase

    toUpperCase is a function and must be called with parentheses to get the uppercase string.
  2. Step 2: Verify other parts

    WebSocket.Server is correct, 'message' event is correct, port can be a number.
  3. Final Answer:

    msg.toUpperCase should be called as a function: msg.toUpperCase() -> Option D
  4. Quick Check:

    Call string methods with () [OK]
Hint: String methods need () to execute, not just reference [OK]
Common Mistakes:
  • Forgetting parentheses on string methods
  • Using wrong event names like 'onMessage'
  • Confusing WebSocket server creation syntax
5. You want to build a Node.js WebSocket server that broadcasts any message received from one client to all connected clients except the sender. Which code snippet correctly implements this behavior?
hard
A. wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
B. wss.on('connection', ws => { ws.on('message', message => { ws.send(message); }); });
C. wss.on('connection', ws => { ws.on('message', message => { wss.send(message); }); });
D. wss.on('message', message => { wss.clients.forEach(client => client.send(message)); });

Solution

  1. Step 1: Understand broadcasting logic

    Broadcast means sending message to all clients except the sender, checking if client connection is open.
  2. 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.
  3. Final Answer:

    Option A code snippet correctly broadcasts to all except sender -> Option A
  4. Quick Check:

    Broadcast = send to all except sender with readyState check [OK]
Hint: Use wss.clients.forEach and skip sender to broadcast [OK]
Common Mistakes:
  • Sending message only back to sender
  • Calling send on wss object instead of clients
  • Not checking client.readyState before sending
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard