📖 Scenario: You want to create a simple chat server that uses WebSocket protocol to allow real-time communication between clients and the server.
🎯 Goal: Build a basic WebSocket server using Node.js that accepts client connections, listens for messages, and sends back a confirmation message.
📋 What You'll Learn
Create a WebSocket server using the ws library
Set up a port number configuration variable
Listen for client connections and messages
Send a confirmation message back to the client
💡 Why This Matters
🌍 Real World
WebSocket servers are used in real-time applications like chat apps, live notifications, and online games where instant communication is needed.
💼 Career
Understanding WebSocket protocol and how to implement it with Node.js is valuable for backend developers working on interactive web applications.
Progress0 / 4 steps
1
Set up WebSocket server import and initial server
Write code to import the WebSocketServer class from the ws library and create a new WebSocket server instance called wss that listens on port 8080.
Node.js
Hint
Use require('ws') to import and create a new WebSocketServer with the port option set to 8080.
2
Add a port configuration variable
Create a constant variable called PORT and set it to 8080. Then update the WebSocket server instance wss to use this PORT variable instead of the hardcoded number.
Node.js
Hint
Define const PORT = 8080; and use it in the WebSocketServer constructor.
3
Listen for client connections and messages
Add an event listener on wss for the 'connection' event with a callback function that takes a ws parameter. Inside this callback, add another event listener on ws for the 'message' event that receives a message parameter.
Node.js
Hint
Use wss.on('connection', (ws) => { ... }) and inside it ws.on('message', (message) => { ... }).
4
Send confirmation message back to client
Inside the message event listener, send a message back to the client using ws.send() with the text 'Message received'.
Node.js
Hint
Use ws.send('Message received') inside the message event listener.
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
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 B
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
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 C
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'?
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
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 D
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?