Lecture Notes Of Class
25: Working with WebSockets in Node.js
Objective:
By the
end of this lecture, students will:
- Understand
what WebSockets are and how they work.
- Learn
how to use WebSockets in Node.js.
- Implement
a simple chat application using WebSockets.
Introduction
to WebSockets
What
are WebSockets?
WebSockets
provide a full-duplex communication channel over a single TCP connection,
allowing real-time, bidirectional communication between a client and a server.
Unlike HTTP, which follows a request-response model, WebSockets enable a
persistent connection where the server can send updates to the client without
waiting for a request.
Key
Features of WebSockets
- Full-duplex communication
– Both client and server can send and receive messages at any time.
- Low latency
– Reduces delay compared to traditional HTTP polling or AJAX requests.
- Persistent connection
– The connection remains open until explicitly closed by either party.
- Efficient
– Reduces overhead by avoiding repeated HTTP handshakes.
How
WebSockets Work
1.
Handshake Process – The client sends a
WebSocket handshake request to the server over HTTP.
2.
Protocol Upgrade – The server upgrades
the connection to WebSocket.
3.
Persistent Communication
– The connection remains open, allowing both parties to send and receive
messages.
4.
Closure – Either the client or
the server can close the connection.
WebSocket
URL Format
WebSocket
connections use ws://
(for non-secure connections) and wss://
(for secure connections).
arduinows://server_address:portwss://server_address:port
Installing
WebSocket Library in Node.js
Node.js
does not provide built-in WebSocket support, so we use the ws library.
Step
1: Initialize a Node.js Project
shmkdir websocket-democd websocket-demonpm init -y
Step
2: Install the WebSocket Library
shnpm install ws
Creating
a Simple Chat Application Using WebSockets
We will
create a simple WebSocket chat application where multiple clients can connect
and exchange messages.
1.
Creating the WebSocket Server
Create a
file named server.js
and add the following code:
jsconst WebSocket = require('ws'); // Create a WebSocket server on port 8080const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('New client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); // Broadcast the message to all connected clients wss.clients.forEach((client) => { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); ws.on('close', () => { console.log('Client disconnected'); });}); console.log('WebSocket server running on ws://localhost:8080');
2.
Creating the WebSocket Client (Frontend)
Create an
index.html
file with the following code:
html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Chat</title></head><body> <h2>WebSocket Chat Application</h2> <input type="text" id="messageInput" placeholder="Type a message..."> <button onclick="sendMessage()">Send</button> <ul id="messages"></ul> <script> const ws = new WebSocket('ws://localhost:8080'); ws.onmessage = (event) => { const msgList = document.getElementById('messages'); const msgItem = document.createElement('li'); msgItem.textContent = event.data; msgList.appendChild(msgItem); }; function sendMessage() { const input = document.getElementById('messageInput'); ws.send(input.value); input.value = ''; } </script></body></html>
3.
Running the WebSocket Chat Application
Start the WebSocket Server
shnode server.js
Open the Client
1.
Open index.html
in multiple browser tabs.
2.
Type a message and send it.
3.
Observe that messages appear in all open
tabs.
Conclusion
- WebSockets
enable real-time communication between clients and servers.
- The
wslibrary in Node.js simplifies WebSocket implementation. - A
simple chat application demonstrates how multiple clients can communicate
in real time.
Lab
Tasks
Task
1: Install the WebSocket Library
- Initialize
a Node.js project.
- Install
the
wsWebSocket library.
Task
2: Create a Simple Chat Application
- Implement
a WebSocket server using Node.js.
- Develop
a client-side interface using HTML and JavaScript.
- Test
real-time communication using multiple browser tabs.
Would you
like additional features like user names, timestamps, or message history? 🚀
2/2
You
said:
Write solutions: Lab
Tasks Task 1: Install the WebSocket Library Initialize a Node.js project.
Install the ws WebSocket library. Task 2: Create a Simple Chat Application
Implement a WebSocket server using Node.js. Develop a client-side interface
using HTML and JavaScript. Test real-time communication using multiple browser
tabs.
ChatGPT
said:
Here are
the detailed solutions for the lab tasks:
Task
1: Install the WebSocket Library
Step
1: Initialize a Node.js Project
1.
Open a terminal and create a new folder
for the project:
shmkdir websocket-chatcd websocket-chat
2.
Initialize a Node.js project by running:
shnpm init -y
This will generate a package.json file.
Step
2: Install the WebSocket Library
1.
Install the ws
WebSocket library:
shnpm install ws
2.
Verify installation by checking the node_modules folder and package.json dependencies.
Task
2: Create a Simple Chat Application
Step
1: Implement a WebSocket Server
Create a
file server.js
and add the following code:
jsconst WebSocket = require('ws'); // Create WebSocket server on port 8080const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('New client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); // Broadcast message to all connected clients wss.clients.forEach((client) => { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); ws.on('close', () => { console.log('Client disconnected'); });}); console.log('WebSocket server running on ws://localhost:8080');
Step
2: Develop the Client-Side Interface
Create an
index.html
file with the following code:
html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Chat</title></head><body> <h2>WebSocket Chat Application</h2> <input type="text" id="messageInput" placeholder="Type a message..."> <button onclick="sendMessage()">Send</button> <ul id="messages"></ul> <script> const ws = new WebSocket('ws://localhost:8080'); ws.onmessage = (event) => { const msgList = document.getElementById('messages'); const msgItem = document.createElement('li'); msgItem.textContent = event.data; msgList.appendChild(msgItem); }; function sendMessage() { const input = document.getElementById('messageInput'); ws.send(input.value); input.value = ''; } </script></body></html>
Step
3: Run and Test the Application
1.
Start the WebSocket Server
shnode server.js
Output:
arduinoWebSocket server running on ws://localhost:8080
2.
Open the Client in Multiple Browser Tabs
o Open
index.html in a
browser.
o Open
the same page in multiple tabs.
o Type
a message and send it.
o Observe
that the message appears in all open tabs in real-time.
🎯 Conclusion
- Successfully
installed the
wsWebSocket library. - Implemented
a WebSocket server using Node.js.
- Created
a simple real-time chat application using WebSockets.
- Verified
real-time communication across multiple clients.
Would you
like to extend the chat app with usernames or message history? 🚀
You
said:
WRITE 10 ASSIGNMENTS FROM
ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details
ChatGPT
said:
Here are 10
detailed assignments based on the concept of WebSockets in
Node.js, each with step-by-step solutions and explanations.
Assignment
1: Understanding WebSockets and How They Work
Problem
Statement
Explain
the working of WebSockets with an example. Compare WebSockets with traditional
HTTP communication methods like polling and long polling.
Solution
Step
1: Understanding WebSockets
- WebSockets
allow real-time, bidirectional communication between a client and a server
over a persistent connection.
- Unlike
HTTP, where the client must request data, WebSockets let the server push
updates as they occur.
Step
2: WebSocket vs HTTP Communication
|
Feature |
WebSockets |
HTTP
(Polling / Long Polling) |
|
Connection Type |
Persistent |
Repeated requests |
|
Latency |
Low |
High (due to
request-response overhead) |
|
Communication |
Bidirectional |
Mostly client-initiated |
|
Efficiency |
High |
Low (frequent HTTP
headers) |
Step
3: Example Implementation
jsconst WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.send('Hello from server'); ws.on('message', (message) => console.log(`Received: ${message}`));});
- Run:
node server.js - Test
using a WebSocket client (e.g., browser console):
jslet ws = new WebSocket('ws://localhost:8080');ws.onmessage = (event) => console.log(event.data);ws.send('Hello Server');
Assignment
2: Installing and Setting Up WebSockets in Node.js
Problem
Statement
Set up a
Node.js WebSocket server and verify the installation of the ws library.
Solution
Step
1: Initialize a Node.js Project
shmkdir websocket-democd websocket-demonpm init -y
Step
2: Install ws WebSocket Library
shnpm install ws
Step
3: Verify Installation
Check package.json for "ws": "^X.Y.Z"
under dependencies.
Assignment
3: Implement a Basic WebSocket Server
Problem
Statement
Create a
WebSocket server that sends a welcome message when a client connects.
Solution
Step
1: Write the WebSocket Server Code
jsconst WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.send('Welcome to WebSocket Server!');});
Step
2: Start the Server
shnode server.js
Step
3: Test with a Client
Open
browser console and type:
jslet ws = new WebSocket('ws://localhost:8080');ws.onmessage = (event) => console.log(event.data);
Assignment
4: Sending and Receiving Messages Using WebSockets
Problem
Statement
Modify
the WebSocket server to allow clients to send messages and broadcast them to
all connected clients.
Solution
Step
1: Implement Message Broadcasting
jsconst WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(`Client says: ${message}`); } }); });});
Step
2: Test the Server
Open
multiple browser tabs and run:
jslet ws = new WebSocket('ws://localhost:8080');ws.onmessage = (event) => console.log(event.data);ws.send('Hello Server');
Assignment
5: Creating a WebSocket Client UI
Problem
Statement
Develop a
simple HTML page that allows users to send and receive WebSocket messages.
Solution
Step
1: Create index.html
html<!DOCTYPE html><html><head> <title>WebSocket Chat</title></head><body> <input type="text" id="messageInput"> <button onclick="sendMessage()">Send</button> <ul id="messages"></ul> <script> const ws = new WebSocket('ws://localhost:8080'); ws.onmessage = (event) => { let item = document.createElement('li'); item.textContent = event.data; document.getElementById('messages').appendChild(item); }; function sendMessage() { const input = document.getElementById('messageInput'); ws.send(input.value); input.value = ''; } </script></body></html>
Assignment
6: Adding User Identification in Chat Messages
Problem
Statement
Modify
the chat application to allow users to enter their names before sending
messages.
Solution
Modify index.html:
html<input type="text" id="username" placeholder="Enter your name"><input type="text" id="messageInput"><button onclick="sendMessage()">Send</button>
Modify sendMessage() function:
jsfunction sendMessage() { const username = document.getElementById('username').value; const message = document.getElementById('messageInput').value; ws.send(`${username}: ${message}`);}
Assignment
7: Handling WebSocket Connection Errors
Problem
Statement
Modify
the WebSocket server to handle connection errors.
Solution
Modify server.js:
jsws.on('error', (error) => { console.error('WebSocket Error:', error);});
Modify
the client:
jsws.onerror = (error) => { console.error('WebSocket Error:', error);};
Assignment
8: Implementing WebSocket Connection Closure Handling
Problem
Statement
Handle
disconnections properly and notify remaining users.
Solution
Modify server.js:
jsws.on('close', () => { console.log('Client disconnected');});
Assignment
9: Secure WebSockets with HTTPS (WSS)
Problem
Statement
Set up a
secure WebSocket server using wss://.
Solution
Step
1: Install HTTPS Module
shnpm install https
Step
2: Create an HTTPS Server
jsconst fs = require('fs');const https = require('https');const WebSocket = require('ws'); const server = https.createServer({ cert: fs.readFileSync('server.crt'), key: fs.readFileSync('server.key')});const wss = new WebSocket.Server({ server }); server.listen(8443, () => { console.log('Secure WebSocket server running on wss://localhost:8443');});
Assignment
10: Deploying WebSockets on a Cloud Server
Problem
Statement
Deploy
your WebSocket server on a cloud platform like AWS or Heroku.
Solution
Step
1: Set Up a Cloud Instance
- Create
a virtual machine on AWS/Heroku.
Step
2: Install Node.js and Run WebSocket Server
shsudo apt install nodejs npmnode server.js
Would you
like more advanced features like message history storage in a database? 🚀
You
said:
WRITE 50 no of MCQs only
FROM ABOVE CONCEPT with explanation
ChatGPT
said:
Here are 50
multiple-choice questions (MCQs) based on WebSockets in
Node.js, along with detailed explanations for each answer.
Basic
WebSocket Concepts
1.
What is WebSocket used for?
A)
One-way communication
B) Real-time bidirectional communication
C) Only for video streaming
D) File transfer
Answer: B) Real-time bidirectional
communication
Explanation: WebSockets enable real-time, two-way
communication between the client and server without repeated HTTP requests.
2.
How does WebSocket differ from HTTP?
A)
WebSocket is stateless, whereas HTTP is stateful
B) WebSocket requires a new connection for each message
C) WebSocket maintains a persistent connection
D) WebSocket is slower than HTTP
Answer: C) WebSocket maintains a persistent
connection
Explanation: Unlike HTTP, which requires a new
request-response cycle for each interaction, WebSockets keep a single open
connection.
3.
What protocol does WebSocket use?
A) TCP
B) UDP
C) HTTP
D) FTP
Answer: A) TCP
Explanation: WebSockets operate over TCP,
ensuring reliable, ordered, and error-checked data transmission.
4.
What is the default WebSocket port?
A) 21
B) 80
C) 443
D) 8080
Answer: D) 8080
Explanation: While WebSockets can run on any port, they often
use port 8080 for ws:// and port 443 for wss://
(secure WebSockets).
Installing
and Setting Up WebSockets in Node.js
5.
Which Node.js library is commonly used for WebSockets?
A)
socket.io
B) ws
C) express
D) http
Answer: B) ws
Explanation: The ws
package is a lightweight and efficient WebSocket library for Node.js.
6.
How do you install the ws library in a Node.js project?
A) npm install websocket
B) npm install ws
C) npm install socket.io
D) npm install web-socket
Answer: B) npm
install ws
Explanation: The correct command to install the ws library in a Node.js
project is npm install ws.
7.
What function is used to create a WebSocket server in Node.js?
A) new WebSocketServer()
B) WebSocket.Server()
C) new ws.Server()
D) ws.createServer()
Answer: C) new
ws.Server()
Explanation: To create a WebSocket server, use new ws.Server({ port: 8080 })
from the ws library.
WebSocket
Communication and Events
8.
Which event fires when a WebSocket client connects?
A) onopen
B) onmessage
C) onconnection
D) onclose
Answer: A) onopen
Explanation: The onopen
event is triggered when a WebSocket connection is successfully established.
9.
How does a WebSocket client send messages?
A) ws.transmit()
B) ws.send()
C) ws.emit()
D) ws.post()
Answer: B) ws.send()
Explanation: The send()
function is used in WebSockets to transmit messages between the client and
server.
10.
Which event is triggered when a WebSocket message is received?
A) onreceive
B) ondata
C) onmessage
D) onconnect
Answer: C) onmessage
Explanation: The onmessage
event handles incoming messages on a WebSocket connection.
Building
a WebSocket Chat Application
11.
In a WebSocket-based chat application, how do you broadcast a message to all
connected clients?
A) wss.sendAll(message)
B) wss.broadcast(message)
C) ws.clients.forEach(client
=> client.send(message))
D) ws.sendToAll(message)
Answer: C) ws.clients.forEach(client
=> client.send(message))
Explanation: The correct way to broadcast a message is to loop
through all connected clients and send the message.
12.
How do you handle disconnections in a WebSocket server?
A) ws.on('exit', callback)
B) ws.on('disconnect',
callback)
C) ws.on('close', callback)
D) ws.on('stop', callback)
Answer: C) ws.on('close',
callback)
Explanation: The close
event fires when a client disconnects from the WebSocket server.
WebSocket
Security and Performance
13.
What is the main security concern with WebSockets?
A) Slow
speed
B) Large memory usage
C) Cross-site WebSocket hijacking
D) WebSockets cannot be secured
Answer: C) Cross-site WebSocket hijacking
Explanation: WebSockets are vulnerable to cross-site
hijacking, where an attacker connects to an open WebSocket connection
from an unauthorized origin.
14.
How do you secure WebSockets?
A) Use wss:// instead of ws://
B) Enable CORS for all origins
C) Encrypt data using HTTP headers
D) Disable WebSockets for security
Answer: A) Use wss://
instead of ws://
Explanation: Secure WebSockets (wss://)
use TLS encryption to protect data from attackers.
Deploying
WebSockets in Production
15.
Which cloud platforms support WebSocket deployment?
A) AWS
B) Heroku
C) DigitalOcean
D) All of the above
Answer: D) All of the above
Explanation: AWS, Heroku, and DigitalOcean all support
WebSocket deployment using Node.js.
16.
What command is used to deploy a Node.js WebSocket application on Heroku?
A) git push heroku master
B) heroku push origin main
C) deploy heroku websocket
D) heroku upload websocket
Answer: A) git
push heroku master
Explanation: This command pushes the application to Heroku for
deployment.
17.
Which of the following is a WebSocket testing tool?
A)
Postman
B) WebSocket.org Echo Test
C) SoapUI
D) Nmap
Answer: B) WebSocket.org Echo Test
Explanation: WebSocket.org provides an online testing tool for
WebSocket connections.
More
Advanced WebSocket MCQs
18.
What does ws.readyState === WebSocket.OPEN check?
A) If the
server is running
B) If the connection is secure
C) If the WebSocket is open and ready to send messages
D) If the WebSocket is about to close
Answer: C) If the WebSocket is open and
ready to send messages
Explanation: The readyState
property indicates if the WebSocket is open (1),
closing (2), or
closed (3).
19.
What happens if a WebSocket server crashes?
A) All
connected clients will receive an error
B) The clients automatically reconnect
C) Messages will be queued until the server restarts
D) Nothing happens
Answer: A) All connected clients will
receive an error
Explanation: Clients will get a close
event when the WebSocket server crashes.
Would you
like more MCQs or more practical examples? 🚀
You
said:
yes
ChatGPT
said:
Here are 30
more multiple-choice questions (MCQs) on WebSockets in Node.js,
with detailed explanations.
WebSocket
Events and Handlers
20.
What happens when a WebSocket connection is closed?
A) The
server restarts automatically
B) The onclose
event fires
C) The client keeps sending messages
D) The onmessage
event fires
Answer: B) The onclose
event fires
Explanation: When a WebSocket connection closes, the onclose event is triggered,
allowing the server or client to handle disconnections.
21.
How can a WebSocket client detect an error?
A) Using onerror event
B) Using onclose
event
C) Using onfail
event
D) Using catch(error)
Answer: A) Using onerror event
Explanation: The onerror
event is used to handle WebSocket errors.
22.
Which method is used to close a WebSocket connection?
A) ws.disconnect()
B) ws.terminate()
C) ws.close()
D) ws.end()
Answer: C) ws.close()
Explanation: The close()
method is used to close an active WebSocket connection.
23.
What happens if a WebSocket client tries to send a message after the connection
is closed?
A) The
message is delivered normally
B) The message is queued
C) An error occurs
D) The message is ignored silently
Answer: C) An error occurs
Explanation: Trying to send a message on a closed WebSocket
will result in an error.
24.
What is the maximum size of a WebSocket message?
A) 16 KB
B) 64 KB
C) No fixed limit
D) 1 MB
Answer: C) No fixed limit
Explanation: WebSockets don’t have a strict message size
limit, but large messages can be fragmented into smaller frames.
WebSocket
vs Other Communication Protocols
25.
How does WebSocket compare to AJAX polling?
A)
WebSocket is slower
B) WebSocket reduces network overhead
C) AJAX polling is more efficient
D) WebSocket is not used for real-time data
Answer: B) WebSocket reduces network
overhead
Explanation: Unlike AJAX polling, which repeatedly requests
data, WebSockets keep a persistent connection, reducing unnecessary HTTP
requests.
26.
Can WebSockets be used with REST APIs?
A) No,
WebSockets replace REST APIs
B) Yes, WebSockets can complement REST APIs
C) Only in HTTP/2
D) WebSockets only work with GraphQL
Answer: B) Yes, WebSockets can complement
REST APIs
Explanation: WebSockets provide real-time updates, while REST
APIs are useful for CRUD operations.
27.
Which is more suitable for stock market updates?
A) REST
API
B) WebSockets
C) GraphQL
D) FTP
Answer: B) WebSockets
Explanation: WebSockets allow real-time bidirectional
communication, making them ideal for stock market updates.
Advanced
WebSocket Concepts
28.
What does ping do in a WebSocket connection?
A) Sends
a test message
B) Checks if the connection is alive
C) Closes the connection
D) Encrypts data
Answer: B) Checks if the connection is alive
Explanation: The ping
message is sent to check if a WebSocket connection is still active.
29.
How can you handle multiple WebSocket connections in Node.js?
A) Using
WebSocket groups
B) Using an array of connected clients
C) Using multiple WebSocket servers
D) WebSocket doesn’t support multiple connections
Answer: B) Using an array of connected
clients
Explanation: A WebSocket server can track multiple clients
using an array or a Set.
30.
What is WebSocket subprotocol?
A) A
protocol used for WebSocket tunneling
B) A way to define custom communication rules over WebSockets
C) A method to encrypt WebSocket messages
D) Another name for WebSocket API
Answer: B) A way to define custom
communication rules over WebSockets
Explanation: Subprotocols help define additional communication
rules, such as chat or game protocols.
31.
How can WebSockets handle authentication?
A) Using
HTTP headers during the handshake
B) WebSockets don’t support authentication
C) By sending credentials in each message
D) Only via OAuth
Answer: A) Using HTTP headers during the
handshake
Explanation: WebSockets rely on HTTP headers for
authentication before the connection is established.
32.
What is the role of the Sec-WebSocket-Key header?
A)
Encrypts the WebSocket data
B) Prevents unauthorized connections
C) Helps establish a WebSocket handshake
D) Sets the WebSocket timeout
Answer: C) Helps establish a WebSocket
handshake
Explanation: The Sec-WebSocket-Key
header is used in the WebSocket handshake process.
Debugging
and Error Handling in WebSockets
33.
What is the best way to debug a WebSocket connection?
A) Using
console logs
B) Using browser dev tools
C) Using ws.debug()
D) WebSockets cannot be debugged
Answer: B) Using browser dev tools
Explanation: The Network tab in browser DevTools
helps inspect WebSocket connections.
34.
What does error code 1006 indicate in WebSockets?
A) Normal
closure
B) Connection timeout
C) Abnormal disconnection
D) Authentication failure
Answer: C) Abnormal disconnection
Explanation: Code 1006 means the connection
was closed unexpectedly.
WebSocket
Deployment and Performance Optimization
35.
Which tool can be used for WebSocket load testing?
A) Apache
JMeter
B) Postman
C) SoapUI
D) Selenium
Answer: A) Apache JMeter
Explanation: JMeter is a popular tool for
load testing WebSockets.
36.
What is a common technique for scaling WebSocket servers?
A) Using
a single-threaded server
B) Using a WebSocket proxy
C) Disabling persistent connections
D) Running multiple Node.js processes with WebSocket
Answer: D) Running multiple Node.js
processes with WebSocket
Explanation: WebSocket servers scale using clustering or
WebSocket proxies.
37.
What is the role of Nginx in WebSocket deployment?
A) Load
balancing WebSocket connections
B) Converting WebSocket to HTTP
C) Caching WebSocket messages
D) Blocking WebSocket traffic
Answer: A) Load balancing WebSocket
connections
Explanation: Nginx can act as a WebSocket
proxy and load balancer.
WebSockets
and Frontend Development
38.
How does a frontend WebSocket client initiate a connection?
A) new WebSocket(url)
B) WebSocket.connect(url)
C) open WebSocket(url)
D) ws.create(url)
Answer: A) new
WebSocket(url)
Explanation: A WebSocket connection is initiated using new
WebSocket("ws://example.com").
39.
How do you detect WebSocket support in JavaScript?
A) if (WebSocket)
B) WebSocket.supported()
C) if ('WebSocket' in
window)
D) navigator.WebSocket
Answer: C) if
('WebSocket' in window)
Explanation: Checking if
('WebSocket' in window) determines if the browser supports
WebSockets.
40.
What is the use of onopen in a WebSocket client?
A)
Handles incoming messages
B) Sends a connection request
C) Runs when the WebSocket connection is established
D) Terminates the connection
Answer: C) Runs when the WebSocket
connection is established
Explanation: The onopen
event occurs when a WebSocket client successfully connects.
Would you
like more advanced WebSocket MCQs or practical coding
exercises? 🚀
You
said:
yes
ChatGPT
said:
Here are 10
advanced MCQs on WebSockets in Node.js, along with detailed
explanations.
Advanced
WebSockets MCQs
41.
What is the main advantage of WebSockets over HTTP long polling?
A)
WebSockets reduce server load and latency
B) WebSockets use less secure connections
C) HTTP long polling is faster than WebSockets
D) WebSockets consume more bandwidth than polling
Answer: A) WebSockets reduce server load and
latency
Explanation: WebSockets establish a persistent connection,
reducing the need for repeated HTTP requests, leading to lower latency
and server load compared to HTTP long polling.
42.
Which of the following is a security concern in WebSockets?
A)
WebSockets use too much CPU
B) WebSockets are not encrypted by default
C) WebSockets do not support cross-origin requests
D) WebSockets require a new connection for each message
Answer: B) WebSockets are not encrypted by
default
Explanation: WebSockets use ws://
(unencrypted) by default, so wss:// (WebSocket Secure) should
be used to ensure encryption.
43.
What is the default port for WebSockets over HTTPS (WSS)?
A) 80
B) 443
C) 8080
D) 3000
Answer: B) 443
Explanation: WebSockets over HTTPS (WSS) use
port 443, just like regular HTTPS traffic.
44.
Which of the following statements is true about WebSockets and CORS?
A)
WebSockets follow the same-origin policy like AJAX requests
B) WebSockets do not require CORS handling
C) WebSockets cannot connect to a different origin
D) WebSockets reject all cross-origin requests
Answer: B) WebSockets do not require CORS
handling
Explanation: Unlike AJAX, WebSockets bypass CORS
restrictions since they do not use standard HTTP request-response mechanisms.
45.
How does WebSocket handle binary data?
A)
WebSockets can only send text messages
B) WebSockets encode binary data in JSON
C) WebSockets support ArrayBuffer
and Blob
D) WebSockets convert binary data to Base64
Answer: C) WebSockets support ArrayBuffer and Blob
Explanation: WebSockets can send binary data
using ArrayBuffer
and Blob types.
46.
Which method is used to check if a WebSocket is still open before sending a
message?
A) ws.status === "open"
B) ws.isConnected()
C) ws.readyState ===
WebSocket.OPEN
D) ws.active === true
Answer: C) ws.readyState
=== WebSocket.OPEN
Explanation: The readyState property
indicates whether the WebSocket connection is open, closed, or
connecting.
47.
What happens if a WebSocket connection is closed unexpectedly?
A) The
browser reloads the page
B) The onerror and
onclose
events are triggered
C) The WebSocket automatically reconnects
D) The WebSocket sends an HTTP request
Answer: B) The onerror
and onclose
events are triggered
Explanation: If a WebSocket disconnects unexpectedly,
the onerror and onclose events help handle
the error and clean up resources.
48.
How can WebSockets handle reconnection when a client disconnects?
A) Use a
loop to create a new WebSocket connection
B) Automatically retry using an event listener
C) Manually reinitialize the WebSocket connection in onclose
D) WebSockets do not support reconnections
Answer: C) Manually reinitialize the
WebSocket connection in onclose
Explanation: WebSockets do not auto-reconnect,
so developers must implement manual reconnection inside the onclose event.
49.
What is the purpose of the ws.ping() method in a WebSocket server?
A) To
send a message to the client
B) To check if the connection is still active
C) To close the connection
D) To broadcast data to all clients
Answer: B) To check if the connection is
still active
Explanation: The ping()
method allows a WebSocket server to verify if a client is still
connected and responding.
50.
Which technique can be used to scale WebSocket servers for thousands of
concurrent users?
A) Using
multiple servers with a load balancer
B) Running WebSockets in single-threaded mode
C) Restarting the server every few minutes
D) Avoiding WebSockets for high-traffic applications
Answer: A) Using multiple servers with a
load balancer
Explanation: To handle large-scale WebSocket traffic,
use a load balancer (e.g., Nginx, HAProxy) and distribute
connections across multiple servers.

No comments:
Post a Comment