Bird
Raised Fist0
Node.jsframework~20 mins

Server-Sent Events alternative in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Understanding WebSocket as an SSE Alternative
Which of the following best describes why WebSocket is often used as an alternative to Server-Sent Events (SSE) in Node.js applications?
AWebSocket allows two-way communication between client and server, unlike SSE which is one-way from server to client.
BWebSocket only supports text data, while SSE supports binary data.
CWebSocket requires less server resources because it uses HTTP/2, while SSE uses HTTP/1.1.
DWebSocket automatically retries connections without any client-side code, unlike SSE.
Attempts:
2 left
💡 Hint
Think about the direction of data flow and interaction between client and server.
❓ component_behavior
intermediate
1:30remaining
Behavior of a WebSocket Server in Node.js
Given the following Node.js WebSocket server code snippet, what will happen when a client sends a message to the server?
Node.js
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', ws => {
  ws.on('message', message => {
    ws.send(`Server received: ${message}`);
  });
});
AThe server will broadcast the received message to all connected clients.
BThe server will echo back the received message prefixed with 'Server received: ' to the same client.
CThe server will close the connection after receiving the message.
DThe server will ignore the message and not respond.
Attempts:
2 left
💡 Hint
Look at the ws.send call inside the message event handler.
📝 Syntax
advanced
2:00remaining
Correct WebSocket Client Connection Syntax
Which of the following Node.js client code snippets correctly establishes a WebSocket connection to ws://localhost:8080 and logs messages received from the server?
A
const ws = new WebSocket('ws://localhost:8080');
ws.on('message', function(data) { console.log(data); });
B
const ws = new WebSocket('ws://localhost:8080');
ws.addEventListener('message', event => console.log(event.data));
C
import WebSocket from 'ws';
const ws = new WebSocket('http://localhost:8080');
ws.onmessage = data => console.log(data);
D
import WebSocket from 'ws';
const ws = new WebSocket('ws://localhost:8080');
ws.on('message', data => console.log(`Received: ${data}`));
Attempts:
2 left
💡 Hint
Consider the correct import and event listener syntax for Node.js WebSocket client.
🔧 Debug
advanced
2:00remaining
Debugging WebSocket Server Connection Issue
A developer writes this WebSocket server code but clients cannot connect. What is the most likely cause?
Node.js
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 3000 });

wss.on('connection', ws => {
  ws.send('Welcome!');
});
AThe server is listening on port 3000 but clients are connecting to port 8080.
BThe WebSocketServer constructor requires a 'host' option to accept connections.
CThe server must call wss.listen() to start listening for connections.
DThe ws.send call should be inside a 'message' event handler.
Attempts:
2 left
💡 Hint
Check if the client connection URL matches the server port.
❓ state_output
expert
2:30remaining
Output of WebSocket Server Broadcast Implementation
Consider this Node.js WebSocket server code that broadcasts messages to all clients except the sender. What will be logged on the server console after two clients connect and one sends 'Hello'?
Node.js
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', ws => {
  console.log('Client connected');
  ws.on('message', message => {
    console.log(`Received: ${message}`);
    wss.clients.forEach(client => {
      if (client !== ws && client.readyState === 1) {
        client.send(`Broadcast: ${message}`);
      }
    });
  });
});
A
Client connected
Received: Hello
Client connected
B
Received: Hello
Client connected
Client connected
C
Client connected
Client connected
Received: Hello
D
Client connected
Client connected
Received: Broadcast: Hello
Attempts:
2 left
💡 Hint
Consider the order of events when clients connect and send messages.

Practice

(1/5)
1. What is a key difference between Server-Sent Events (SSE) and WebSockets in Node.js?
easy
A. SSE only allows server-to-client messages, while WebSockets allow two-way communication.
B. SSE supports two-way communication, but WebSockets only send data from server to client.
C. Both SSE and WebSockets only allow server-to-client communication.
D. WebSockets are slower than SSE for sending messages.

Solution

  1. Step 1: Understand SSE communication direction

    Server-Sent Events send updates only from the server to the client, not the other way around.
  2. Step 2: Understand WebSocket communication direction

    WebSockets allow full two-way communication between client and server, enabling interactive real-time data exchange.
  3. Final Answer:

    SSE only allows server-to-client messages, while WebSockets allow two-way communication. -> Option A
  4. Quick Check:

    Communication direction = A [OK]
Hint: Remember: SSE is one-way, WebSocket is two-way [OK]
Common Mistakes:
  • Thinking SSE supports two-way communication
  • Confusing WebSocket speed with direction
  • Assuming both are identical in communication
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 = require('ws'); const server = new ws.Server(8080);
B. const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 8080 });
C. import ws from 'ws'; const server = ws.createServer(8080);
D. const ws = require('ws'); const server = ws.createServer({ port: 8080 });

Solution

  1. Step 1: Identify correct import and usage

    The 'ws' library is imported as WebSocket, and the server is created with new WebSocket.Server({ port: 8080 }).
  2. Step 2: Check syntax correctness

    The other options contain syntax errors, such as incorrect constructor arguments, non-existent methods like 'createServer', or invalid import styles.
  3. Final Answer:

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

    Correct WebSocket server syntax = C [OK]
Hint: Use 'new WebSocket.Server' with correct import [OK]
Common Mistakes:
  • Using wrong class name or method
  • Mixing import styles incorrectly
  • Calling non-existent createServer method
3. Given this Node.js WebSocket server code snippet, what will be logged when a client sends 'Hello'?
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
  socket.on('message', message => {
    console.log(`Received: ${message}`);
    socket.send(`Echo: ${message}`);
  });
});
medium
A. Echo: Hello
B. Hello
C. Received: Hello
D. Error: message event not handled

Solution

  1. Step 1: Analyze message event handler

    When the client sends 'Hello', the server logs 'Received: Hello' to the console.
  2. Step 2: Understand socket.send effect

    The server sends back 'Echo: Hello' to the client, but this is not logged on the server console.
  3. Final Answer:

    Received: Hello -> Option C
  4. Quick Check:

    Server console logs message = B [OK]
Hint: Console logs received message, not sent echo [OK]
Common Mistakes:
  • Confusing sent message with logged message
  • Expecting client-side output on server console
  • Ignoring event handler logic
4. Identify the error in this Node.js WebSocket server code snippet:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
  socket.on('message', (msg) => {
    socket.send('Received: ' + message);
  });
});
medium
A. The 'message' event handler should be synchronous.
B. The WebSocket server port is missing.
C. The 'connection' event is misspelled.
D. The variable 'message' is undefined inside the message event handler.

Solution

  1. Step 1: Check variable names in event handler

    The message event handler uses parameter 'msg' but tries to send 'message', which is undefined.
  2. Step 2: Confirm other code parts

    The port is correctly set, 'connection' event is spelled correctly, and async/sync is not an error here.
  3. Final Answer:

    The variable 'message' is undefined inside the message event handler. -> Option D
  4. Quick Check:

    Variable name mismatch = A [OK]
Hint: Match parameter names exactly inside handlers [OK]
Common Mistakes:
  • Using wrong variable name inside callback
  • Assuming port or event name errors
  • Confusing async requirement for message handler
5. You want to replace Server-Sent Events with WebSockets in a Node.js app to allow clients to send messages back to the server. Which approach best achieves this?
hard
A. Use the 'ws' library to create a WebSocket server that listens for 'message' events from clients and broadcasts updates.
B. Use the 'http' module to send periodic SSE messages and ignore client messages.
C. Use the 'express' module to handle SSE and add a REST API for client messages.
D. Use the 'net' module to create a TCP server for SSE communication.

Solution

  1. Step 1: Identify WebSocket capabilities

    WebSockets allow two-way communication, so using the 'ws' library to listen for client messages fits the requirement.
  2. Step 2: Evaluate other options

    The 'net', 'http', and 'express' with REST API options do not provide true two-way real-time communication; they rely on polling, REST calls, or low-level TCP unsuitable for replacing SSE with bidirectional messaging.
  3. Final Answer:

    Use the 'ws' library to create a WebSocket server that listens for 'message' events from clients and broadcasts updates. -> Option A
  4. Quick Check:

    Two-way real-time communication = D [OK]
Hint: Choose WebSocket server for two-way real-time messaging [OK]
Common Mistakes:
  • Using SSE for two-way communication
  • Confusing HTTP REST with real-time sockets
  • Using low-level TCP instead of WebSocket
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