The ws library is used to create WebSocket servers and clients in Node.js, enabling real-time, two-way communication between a server and browser or other clients.
Click to reveal answer
beginner
How do you create a basic WebSocket server using the ws library?
You create a WebSocket server by importing <code>WebSocketServer</code> from <code>ws</code> and then instantiating it with a port number, like:<br><pre>const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });</pre>
Click to reveal answer
beginner
What event do you listen to for new client connections on a ws WebSocket server?
You listen to the 'connection' event on the WebSocket server instance to handle new client connections.
Click to reveal answer
beginner
How can you send a message to a connected client using the ws library?
You use the send() method on the client WebSocket object inside the 'connection' event handler, like ws.send('Hello client!').
Click to reveal answer
beginner
Why is it important to handle the 'message' event on a WebSocket client connection?
Handling the 'message' event lets the server receive and process data sent from the client, enabling interactive real-time communication.
Click to reveal answer
Which method creates a WebSocket server with the ws library?
Aws.createServer(8080)
Bnew WebSocketServer({ port: 8080 })
Cnew WebSocketClient({ port: 8080 })
Dws.startServer(8080)
✗ Incorrect
The WebSocketServer class is used to create a WebSocket server instance.
What event should you listen to for new client connections?
A'connection'
B'client'
C'open'
D'connect'
✗ Incorrect
The 'connection' event fires when a new client connects to the server.
How do you send a message to a client in ws?
Aclient.send(message)
Bclient.emit('send', message)
Cserver.send(client, message)
Dws.sendToClient(message)
✗ Incorrect
The send() method on the client WebSocket object sends data to that client.
Which of these is NOT a valid use of the ws library?
ACreating a WebSocket server
BCreating a WebSocket client
CHandling HTTP requests
DSending real-time messages
✗ Incorrect
The ws library handles WebSocket connections, not HTTP requests.
What event do you listen to for receiving messages from a client?
A'input'
B'data'
C'receive'
D'message'
✗ Incorrect
The 'message' event is triggered when the server receives data from a client.
Explain how to set up a simple WebSocket server using the ws library in Node.js.
Think about the steps from starting the server to talking with clients.
You got /4 concepts.
Describe the role of the 'connection' and 'message' events in a ws WebSocket server.
Focus on how the server interacts with clients.
You got /4 concepts.
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
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.
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.
Final Answer:
To create WebSocket servers and clients for real-time communication -> Option B
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
Step 1: Recall the correct constructor usage
The ws library uses WebSocketServer constructor with an options object, including the port number.
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.
Final Answer:
const server = new WebSocketServer({ port: 8080 }); -> Option A
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?
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
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.
Step 2: Trace the message flow
When client sends 'Hello', server logs 'Received: Hello' and sends 'Hi client' back to client.
Final Answer:
Server logs 'Received: Hello' and sends 'Hi client' back -> Option D
Quick Check:
Message event logs input and replies = Server logs 'Received: Hello' and sends 'Hi client' back [OK]
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
Step 1: Check method usage on message
The code uses msg.toUpperCase without parentheses, so it passes the function itself instead of calling it.
Step 2: Understand the impact
This causes a runtime error because ws.send expects a string or buffer, not a function reference.
Final Answer:
Using msg.toUpperCase without parentheses causes a runtime error -> Option C
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
Step 1: Understand how to access clients
The wss.clients set contains all connected clients. We must iterate over it to send messages.
Step 2: Check client connection state before sending
Only clients with readyState === WebSocket.OPEN can receive messages safely.
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.
Final Answer:
wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); }); -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.