Bird
Raised Fist0
Node.jsframework~20 mins

ws library for WebSocket server in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Server Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a client sends a message?
Consider this WebSocket server code using the ws library. What will the server send back to the client when the client sends the message "hello"?
Node.js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    ws.send(`Received: ${data}`);
  });
});
AThe client receives: "hello"
BThe client receives: "Received: hello"
CThe client receives: "message: hello"
DThe client receives nothing
Attempts:
2 left
💡 Hint
Look at what the server sends back inside the message event handler.
❓ lifecycle
intermediate
1:30remaining
Which event triggers when a client disconnects?
In the ws WebSocket server, which event should you listen to detect when a client closes the connection?
Node.js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
  // Which event here?
  ws.on('???', () => {
    console.log('Client disconnected');
  });
});
A'close'
B'disconnect'
C'end'
D'exit'
Attempts:
2 left
💡 Hint
Think about the standard WebSocket event for connection closure.
📝 Syntax
advanced
1:30remaining
Which option correctly creates a WebSocket server on port 3000?
Choose the code snippet that correctly creates a WebSocket server listening on port 3000 using the ws library.
Aconst wss = new WebSocketServer({ listen: 3000 });
Bconst wss = new WebSocket.Server(3000);
Cconst wss = new WebSocketServer(port=3000);
Dconst wss = new WebSocketServer({ port: 3000 });
Attempts:
2 left
💡 Hint
Check the correct way to pass options to the WebSocketServer constructor.
🔧 Debug
advanced
2:00remaining
Why does this server not respond to client messages?
Look at this code snippet. The server does not send any response back to clients when they send messages. What is the cause?
Node.js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', (data) => {
    ws.send('Got your message');
  });
});

// Client sends a message but gets no response.
AThe server code is correct; the client likely closed the connection before response.
BThe server does not listen for 'message' events correctly because the callback uses arrow function.
CThe server is missing the 'open' event listener to start sending messages.
DThe server is missing the 'connection' event listener on the WebSocketServer instance.
Attempts:
2 left
💡 Hint
Check if the server code listens to the right events and sends messages properly.
❓ state_output
expert
2:30remaining
How many clients are connected after these events?
Given this server code, how many clients are connected after two clients connect and one disconnects?
Node.js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
let count = 0;
wss.on('connection', function connection(ws) {
  count++;
  ws.on('close', () => {
    count--;
  });
});

// Two clients connect, then one disconnects.
A0
B2
C1
D3
Attempts:
2 left
💡 Hint
Count increments on connection and decrements on close.

Practice

(1/5)
1. What is the main purpose of the ws library in Node.js?
easy
A. To connect to SQL databases
B. To create WebSocket servers and clients for real-time communication
C. To handle HTTP requests and routing
D. To manage file uploads in Node.js applications

Solution

  1. Step 1: Understand the role of ws

    The ws library is designed specifically for WebSocket communication, enabling real-time data exchange between server and client.
  2. Step 2: Compare with other options

    Options A, B, and C relate to other Node.js tasks like file uploads, HTTP routing, and database connections, which are not the focus of ws.
  3. Final Answer:

    To create WebSocket servers and clients for real-time communication -> Option B
  4. Quick Check:

    WebSocket library = real-time communication [OK]
Hint: Remember: ws = WebSocket server/client library [OK]
Common Mistakes:
  • Confusing ws with HTTP or database libraries
  • Thinking ws handles file uploads
  • Assuming ws manages REST API routing
2. Which of the following is the correct way to create a WebSocket server using the ws library?
easy
A. const server = new WebSocketServer({ port: 8080 });
B. const server = new WebSocket({ port: 8080 });
C. const server = new WebSocketServer.listen(8080);
D. const server = ws.createServer(8080);

Solution

  1. Step 1: Recall the correct constructor usage

    The ws library uses WebSocketServer constructor with an options object, including the port number.
  2. Step 2: Check each option's syntax

    const server = new WebSocketServer({ port: 8080 }); correctly uses new WebSocketServer({ port: 8080 }). Options B, C, and D use incorrect constructors or methods not defined in ws.
  3. Final Answer:

    const server = new WebSocketServer({ port: 8080 }); -> Option A
  4. Quick Check:

    Correct constructor syntax = const server = new WebSocketServer({ port: 8080 }); [OK]
Hint: Use new WebSocketServer({ port }) to create server [OK]
Common Mistakes:
  • Using WebSocket instead of WebSocketServer for server creation
  • Calling listen() method which does not exist
  • Using non-existent ws.createServer() method
3. What will the following code output when a client sends the message 'Hello' to the server?
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received: ${message}`);
    ws.send('Hi client');
  });
});
medium
A. Nothing happens because no connection event is handled
B. Server logs 'Hi client' and sends 'Received: Hello' back
C. Server throws an error because message event is invalid
D. Server logs 'Received: Hello' and sends 'Hi client' back

Solution

  1. Step 1: Understand event handling

    The server listens for 'connection' events, then listens for 'message' events on each connection. When a message arrives, it logs the message and sends a reply.
  2. Step 2: Trace the message flow

    When client sends 'Hello', server logs 'Received: Hello' and sends 'Hi client' back to client.
  3. Final Answer:

    Server logs 'Received: Hello' and sends 'Hi client' back -> Option D
  4. Quick Check:

    Message event logs input and replies = Server logs 'Received: Hello' and sends 'Hi client' back [OK]
Hint: Message event logs input, ws.send replies [OK]
Common Mistakes:
  • Confusing message event with connection event
  • Thinking server sends back the received message
  • Assuming message event is invalid
4. Identify the error in this WebSocket server code snippet:
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 3000 });
wss.on('connection', function(ws) {
  ws.on('message', function(msg) {
    ws.send(msg.toUpperCase);
  });
});
medium
A. WebSocketServer should be imported from 'websocket' package
B. The 'connection' event should be 'connect'
C. Using msg.toUpperCase without parentheses causes a runtime error
D. ws.send cannot send strings, only buffers

Solution

  1. Step 1: Check method usage on message

    The code uses msg.toUpperCase without parentheses, so it passes the function itself instead of calling it.
  2. Step 2: Understand the impact

    This causes a runtime error because ws.send expects a string or buffer, not a function reference.
  3. Final Answer:

    Using msg.toUpperCase without parentheses causes a runtime error -> Option C
  4. Quick Check:

    Method call missing () causes error = Using msg.toUpperCase without parentheses causes a runtime error [OK]
Hint: Always call string methods with () to avoid errors [OK]
Common Mistakes:
  • Confusing event names 'connection' vs 'connect'
  • Importing WebSocketServer from wrong package
  • Thinking ws.send cannot send strings
5. You want to broadcast a message to all connected clients using the ws library. Which code snippet correctly sends 'Hello all!' to every client connected to the server?
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });

// Broadcast function here
function broadcast(message) {
  // ???
}
hard
A. wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); });
B. wss.clients.map(client => client.send(message));
C. wss.broadcast(message);
D. wss.send(message);

Solution

  1. Step 1: Understand how to access clients

    The wss.clients set contains all connected clients. We must iterate over it to send messages.
  2. Step 2: Check client connection state before sending

    Only clients with readyState === WebSocket.OPEN can receive messages safely.
  3. Step 3: Verify each option

    wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); }); correctly uses forEach and checks readyState. wss.clients.map(client => client.send(message)); uses map which is not appropriate here. Options A and D use non-existent methods.
  4. Final Answer:

    wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); }); -> Option A
  5. Quick Check:

    Broadcast = forEach + readyState check [OK]
Hint: Use forEach and check readyState before sending [OK]
Common Mistakes:
  • Using map instead of forEach for side effects
  • Calling non-existent broadcast or send on server
  • 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