100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is a WebSocket?

Learn what a WebSocket is, how the handshake works, and why full-duplex, persistent connections power real-time apps like chat and games.

mediumQ11 of 224 in Web Development Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

A WebSocket is a communication protocol that opens a single, persistent, full-duplex connection between client and server over TCP, letting either side send messages at any time without the overhead of repeated HTTP requests.

A WebSocket connection begins as a normal HTTP request with an "Upgrade" header; once the server agrees, the connection switches protocols and stays open, so both client and server can push data whenever they want instead of the client always initiating. This makes WebSockets ideal for real-time features like chat, live notifications, collaborative editing, and multiplayer games, where polling the server repeatedly would be wasteful and slow. Unlike HTTP's request-response cycle, a WebSocket carries lightweight framed messages over the same open connection, cutting per-message overhead dramatically. The trade-off is added complexity: servers must manage many long-lived connections, and clients need reconnect and heartbeat logic to handle drops.

  • Full-duplex โ€” both sides push data without waiting to be asked
  • Low per-message overhead after the initial handshake
  • Ideal for real-time features like chat and live updates
  • Avoids the latency and waste of constant HTTP polling

AI Mentor Explanation

A WebSocket is like a live radio commentary line kept open between the stadium and the studio for the whole match, instead of the studio calling in after every over to ask for an update. Once the line connects, either side can speak the instant something happens โ€” a wicket, a boundary โ€” without redialing. That open, always-on line where either party talks whenever they need to is exactly what a WebSocket gives two programs over the network.

Step-by-Step Explanation

  1. Step 1

    Client sends an upgrade request

    A normal HTTP GET request includes headers asking to switch protocols to WebSocket.

  2. Step 2

    Server accepts the handshake

    The server responds with a 101 Switching Protocols status, and the TCP connection stays open.

  3. Step 3

    Both sides exchange frames

    Either client or server can send lightweight message frames at any time over the open connection.

  4. Step 4

    Connection closes or drops

    Either side can close cleanly, or the app detects a drop and reconnects with backoff/heartbeats.

What Interviewer Expects

  • Understanding that WebSocket starts as an HTTP handshake then upgrades
  • Clear grasp of full-duplex, persistent connection vs request-response
  • Real-world use cases: chat, live feeds, multiplayer, collaborative tools
  • Awareness of reconnect/heartbeat handling for dropped connections

Common Mistakes

  • Confusing WebSockets with plain HTTP polling or long-polling
  • Forgetting that a handshake over HTTP is required before upgrading
  • Not planning for reconnection logic when the connection drops
  • Using WebSockets where simple request-response would suffice, adding needless complexity

Best Answer (HR Friendly)

โ€œA WebSocket is a way for a browser and a server to keep a connection open and talk back and forth in real time, instead of the browser having to keep asking "anything new?" It is what powers things like live chat, live notifications, and multiplayer games, where updates need to appear instantly without repeatedly reloading or requesting data.โ€

Code Example

Basic WebSocket client and server
// Client (browser)
const socket = new WebSocket("wss://example.com/chat")
socket.onopen = () => socket.send("hello from client")
socket.onmessage = (event) => console.log("received:", event.data)

// Server (Node.js, using the "ws" library)
const { WebSocketServer } = require("ws")
const wss = new WebSocketServer({ port: 8080 })
wss.on("connection", (ws) => {
  ws.on("message", (msg) => {
    ws.send("echo: " + msg) // push data back anytime
  })
})

Follow-up Questions

  • How does a WebSocket handshake differ from a normal HTTP request?
  • What is the difference between WebSockets and Server-Sent Events?
  • How would you scale WebSocket connections across multiple servers?
  • How do you handle authentication for a WebSocket connection?

MCQ Practice

1. What HTTP status code signals a successful WebSocket handshake upgrade?

101 Switching Protocols tells the client the connection is upgrading from HTTP to WebSocket.

2. What best describes WebSocket communication once connected?

WebSockets are full-duplex: either endpoint can send messages at any time over the same open connection.

3. Which use case is a strong fit for WebSockets?

Real-time, bidirectional, frequent updates (like multiplayer games) are the classic WebSocket use case.

Flash Cards

What protocol does a WebSocket start as before upgrading? โ€” HTTP โ€” it begins as an HTTP request with an Upgrade header.

What does full-duplex mean for WebSockets? โ€” Both client and server can send messages independently at any time.

Name two typical WebSocket use cases. โ€” Live chat and multiplayer games (also live notifications, collaborative editing).

What must clients handle when a WebSocket connection drops? โ€” Reconnection logic and heartbeats to detect and recover from disconnects.

1 / 4

Continue Learning