WebSockets Comprehensive Quiz & Projects
30 questions on WebSockets Tutorial.
Question 1: How does a WebSocket connection begin?
- A. By initiating a UDP broadcast packet across local routers.
- B. By sending a standard HTTP request with an Upgrade header, upgrading the connection to a persistent TCP stream. β (correct answer)
- C. By loading a specialized client browser plugin.
- D. By executing a direct SQL database connection from JavaScript.
Explanation: WebSockets use the HTTP protocol for the handshake. Once successful, the connection upgrades to full-duplex TCP.
Question 2: What is the primary architectural difference between HTTP and WebSockets?
- A. HTTP is encrypted, while WebSockets do not support SSL.
- B. HTTP is a stateless request-response protocol, while WebSockets provide a stateful, persistent, full-duplex connection. β (correct answer)
- C. WebSockets are limited to sending text data.
- D. HTTP runs faster over slow networks.
Explanation: HTTP requires the client to pull data. WebSockets allow the server to push data instantly to the client over an open channel.
Question 3: When scaling a WebSocket application across multiple servers, how does a Redis Pub/Sub backplane resolve message routing?
- A. It stores all messages in SQL databases.
- B. It routes all connections through a single main server.
- C. It acts as an event bus, broadcasting messages published by one server to all other servers so they can push to their connected clients. β (correct answer)
- D. It encrypts payloads to prevent header interception.
Explanation: Since client connections are split across servers, the Redis backplane synchronizes broadcasts across all nodes.
Question 4: Why should developers configure Ping and Pong frames in their WebSocket implementations?
- A. To calculate network latency and show ping values on the frontend.
- B. To act as a heartbeat mechanism, preventing connection timeouts and detecting dead connections. β (correct answer)
- C. To play arcade game metrics during data transfers.
- D. To validate JSON formats of the message payloads.
Explanation: Ping/Pong frames verify that the remote client is still responsive, allowing servers to close dead TCP channels and free resources.
Question 5: When hosting WebSockets behind Nginx, what configuration headers are required to proxy connections successfully?
- A. Content-Type and Authorization
- B. Upgrade $http_upgrade and Connection "upgrade" β (correct answer)
- C. Cache-Control and Access-Control-Allow-Origin
- D. Host and X-Forwarded-Proto
Explanation: Nginx must be configured to pass the Upgrade and Connection header attributes to backend servers to support handshakes.
Question 6: Which secure protocol prefix represents WebSockets over TLS/SSL?
- A. ws://
- B. wss:// β (correct answer)
- C. http://
- D. https://
Explanation: wss:// handles secure WebSocket streams, analogous to HTTPS for standard web pages.
Question 7: Which JavaScript event handler is called when a new message is received from the server?
- A. onopen
- B. onmessage β (correct answer)
- C. onclose
- D. onerror
Explanation: The onmessage callback triggers whenever the browser receives data packets from the open connection.
Question 8: Why are browsers exempt from enforcing CORS on WebSocket connections?
- A. WebSockets are secure by default.
- B. The WebSocket protocol was designed before CORS, leaving servers responsible for validating the 'Origin' header during the initial handshake. β (correct answer)
- C. WebSockets do not transmit cookies.
- D. Browsers block WebSockets to external domains.
Explanation: Cross-Site WebSocket Hijacking (CSWSH) is a risk because browsers submit cookies with the upgrade request, requiring origin checks.
Question 9: Which method is used to send text strings from browsers to servers via WebSockets?
- A. socket.write()
- B. socket.send() β (correct answer)
- C. socket.emit()
- D. socket.post()
Explanation: The native WebSocket send() method pushes text or binary data across open TCP sockets.
Question 10: What happens to a WebSocket connection if the client device loses Wi-Fi?
- A. The connection stays active.
- B. The socket is closed, triggering the onclose event handler. β (correct answer)
- C. The socket falls back to HTTP automatically.
- D. The browser restarts.
Explanation: Network cuts terminate TCP sockets, requiring developers to write reconnection loops.
Question 11: What is the function of the subprotocol argument in the WebSocket constructor (e.g. new WebSocket(url, protocols))?
- A. It speeds up handshake resolutions.
- B. It specifies custom application-level protocols (e.g., soap or json) that the client wants to use, allowing the server to select compatibility. β (correct answer)
- C. It encrypts the payload structure.
- D. It maps fallback HTTP servers.
Explanation: Subprotocols allow clients and servers to negotiate data formatting structures during handshakes.
Question 12: Which HTTP status code indicates that the server is upgrading the connection to WebSockets?
- A. 200 OK
- B. 101 Switching Protocols β (correct answer)
- C. 201 Created
- D. 503 Service Unavailable
Explanation: Status 101 verifies the server accepted the Upgrade request, transitioning to TCP streams.
Question 13: What is a popular JavaScript library that wraps WebSockets, adding features like auto-reconnection and rooms?
- A. Express
- B. Socket.IO β (correct answer)
- C. Axios
- D. jQuery
Explanation: Socket.IO simplifies real-time setups by adding high-level abstracts and polling fallbacks.
Question 14: How do you implement client-to-client messaging in WebSockets?
- A. Clients send packets directly to each other's IPs.
- B. The sending client sends the message to the server, which identifies the target recipient and forwards the message to their active socket. β (correct answer)
- C. By utilizing SQL database replication.
- D. Client-to-client messaging is not supported.
Explanation: WebSockets pass traffic through central servers, which route messages to target sockets.
Question 15: What is the difference between Server-Sent Events (SSE) and WebSockets?
- A. SSE is faster and runs on UDP.
- B. SSE is uni-directional (server-to-client) over HTTP, while WebSockets are bi-directional (full-duplex) over TCP. β (correct answer)
- C. WebSockets are limited to sending text.
- D. There is no difference.
Explanation: SSE is ideal for read-only feeds (news updates); WebSockets are suited for interactive apps (chats).
Question 16: What does the 'readyState' attribute of a WebSocket object represent?
- A. The browser window size.
- B. The connection status (0: CONNECTING, 1: OPEN, 2: CLOSING, 3: CLOSED). β (correct answer)
- C. The size of the message queue.
- D. The network latency in milliseconds.
Explanation: readyState must be 1 (OPEN) before you can push messages via socket.send().
Question 17: What is a 'WebSocket Hijacking' attack (CSWSH)?
- A. Flooding the server with handshake requests.
- B. A CSRF-like attack where a malicious site opens a WebSocket connection to a target app, utilizing the victim's browser session cookies to read private data. β (correct answer)
- C. Hacking the database server locally.
- D. Modifying JS files on client hosts.
Explanation: CSWSH is prevented by verifying that the 'Origin' handshake header matches trusted domains.
Question 18: What is the default port for secure WebSockets (wss://)?
- A. 80
- B. 443 β (correct answer)
- C. 8080
- D. 22
Explanation: Secure WebSockets run over port 443 (standard HTTPS port), bypassing firewalls easily.
Question 19: Why is the 'wss://' protocol preferred over 'ws://' in production?
- A. wss:// is faster and uses less CPU memory.
- B. wss:// encrypts traffic, protecting data from sniffing and preventing corporate proxies from dropping connections. β (correct answer)
- C. ws:// is deprecated in all modern browsers.
- D. ws:// does not support JSON.
Explanation: Encryption stops proxies from reading HTTP headers, letting the Upgrade packet pass.
Question 20: How do you scale WebSockets horizontally using a load balancer?
- A. By configuring the load balancer to close idle connections.
- B. By enabling 'session affinity' (sticky sessions) so the client stays connected to the same server node. β (correct answer)
- C. By routing connections randomly on every packet.
- D. Horizontal scaling is not supported for WebSockets.
Explanation: Sticky sessions ensure the persistent TCP handshake routes to the same node holding connection memory.
Question 21: Which JS event handler runs if a connection setup fails?
- A. onclose
- B. onerror β (correct answer)
- C. onmessage
- D. onstop
Explanation: onerror catches connection drops or handshake rejections, aiding debugging.
Question 22: What does a WebSocket 'frame' contain?
- A. An HTML frame element.
- B. Protocol overhead headers (opcode, length, masking key) and the data payload itself. β (correct answer)
- C. The database index map.
- D. The CSS stylesheet variables.
Explanation: Frames parse inputs into chunks, masking payloads to prevent cache poisoning.
Question 23: Why is payload masking mandatory for client-to-server frames?
- A. To compress data size.
- B. To prevent network proxy caching servers from misinterpreting payloads as cached HTTP requests (preventing cache poisoning). β (correct answer)
- C. To validate JSON schemes.
- D. To encrypt data blocks.
Explanation: Masking XORs client inputs, scrambling bytes so intermediating firewalls don't read patterns.
Question 24: Which package is standard for building WebSocket servers in Node.js?
- A. express
- B. ws β (correct answer)
- C. request
- D. body-parser
Explanation: The ws library is the barebones WebSocket client/server standard in Node.
Question 25: How does HTTP polling differ from WebSockets?
- A. Polling is faster.
- B. Polling requires clients to repeatedly send HTTP requests to check for new data, creating high overhead, while WebSockets push data dynamically over a single pipe. β (correct answer)
- C. Polling does not use cookies.
- D. There is no difference.
Explanation: Polling floods servers with requests; WebSockets keep a single open connection for data flow.
Question 26: What does it mean that WebSockets are 'stateful' on the backend?
- A. They save files to server disks.
- B. The server keeps the socket connection object alive in memory, retaining user state and context throughout the connection lifespan. β (correct answer)
- C. They are managed by React state managers.
- D. They do not support variables.
Explanation: Stateful backends maintain connection references, allowing push alerts at high memory costs.
Question 27: What is the default port for unsecure WebSockets (ws://)?
- A. 443
- B. 80 β (correct answer)
- C. 8080
- D. 21
Explanation: ws:// uses port 80, the default port for unencrypted web communication.
Question 28: What is the function of the client handshake header 'Connection: Upgrade'?
- A. It updates the browser version.
- B. It informs the server that the client wants to transition from the current HTTP session to a different protocol (WebSockets). β (correct answer)
- C. It connects to the nearest databases.
- D. It compiles CSS variables.
Explanation: Connection: Upgrade is a standard requirement for switching protocols via HTTP headers.
Question 29: What is the purpose of the 'Sec-WebSocket-Key' header in handshakes?
- A. To encrypt the message payload.
- B. To provide a randomized string that the server hashes and returns to prove it understands the WebSocket protocol (preventing cached responses). β (correct answer)
- C. To identify the user's password.
- D. To authenticate the client's IP.
Explanation: The key prevents proxies from returning cached responses, confirming the endpoint is active.
Question 30: Which JS event handler executes when the WebSocket connection is closed?
- A. onend
- B. onclose β (correct answer)
- C. ondisconnect
- D. onstop
Explanation: onclose runs when sockets terminate, letting developers restart reconnection intervals.