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

What is the WebSocket Protocol?

Learn what WebSocket is, how the HTTP upgrade handshake works, and why it enables real-time full-duplex communication.

mediumQ188 of 224 in Computer Networks Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

WebSocket is a protocol that upgrades a single HTTP connection into a persistent, full-duplex TCP channel, allowing a client and server to send messages to each other at any time without the overhead of opening a new HTTP request for every message.

A WebSocket connection starts as a normal HTTP request carrying an "Upgrade: websocket" header; if the server agrees, it responds with a 101 Switching Protocols status, and from that point the same underlying TCP connection is repurposed to carry WebSocket frames instead of HTTP requests and responses. Because the connection stays open and is full-duplex, either side can push a message at any time β€” the server does not need to wait for the client to ask, unlike plain HTTP's request/response model β€” which is what makes WebSocket suitable for chat apps, live notifications, collaborative editing, and trading dashboards. Each WebSocket message is wrapped in a lightweight frame (far smaller than a full HTTP header set), so the per-message overhead after the initial handshake is minimal compared to repeatedly polling an HTTP endpoint. WebSocket runs over TCP, so it inherits TCP's reliability and ordering, but as a plain streaming protocol it does not automatically handle reconnection, message replay, or backpressure β€” applications typically add their own heartbeat/ping-pong and reconnect logic on top.

  • Persistent full-duplex channel avoids per-message HTTP handshake overhead
  • Server can push data to the client without the client asking first
  • Lightweight framing after the initial handshake reduces latency
  • Runs over TCP, inheriting reliable, ordered delivery

AI Mentor Explanation

A WebSocket is like a live commentary line kept open between the ground and the studio for the whole match instead of the studio calling the ground fresh before every single update β€” once the line is opened (the handshake), either side can speak whenever something happens, a wicket falls or a boundary is hit, without redialing. A normal HTTP request is like calling the ground, asking for the score, and hanging up, then calling again a minute later just to check. Keeping one open line for the whole innings is exactly what a WebSocket does for continuous, two-way updates.

Step-by-Step Explanation

  1. Step 1

    HTTP handshake

    Client sends an HTTP request with an Upgrade: websocket header to initiate the switch.

  2. Step 2

    Protocol switch

    Server responds with 101 Switching Protocols, repurposing the existing TCP connection.

  3. Step 3

    Full-duplex messaging

    Either side sends lightweight WebSocket frames at any time without a new handshake.

  4. Step 4

    Connection lifecycle

    The application manages heartbeats/reconnects and eventually closes the connection with a close frame.

What Interviewer Expects

  • Explains the HTTP upgrade handshake (101 Switching Protocols)
  • Understands full-duplex, persistent nature vs request/response HTTP
  • Knows WebSocket runs over TCP and inherits its reliability/ordering
  • Mentions applications must add their own heartbeat/reconnect logic

Common Mistakes

  • Thinking WebSocket is a replacement for HTTP entirely rather than an upgrade from it
  • Assuming WebSocket automatically retries or reconnects on its own
  • Confusing WebSocket with long-polling as if they are the same mechanism
  • Forgetting the connection starts as a normal HTTP request before upgrading

Best Answer (HR Friendly)

β€œA WebSocket is a way for a browser and a server to keep a single connection open so they can send messages back and forth instantly, instead of the browser having to keep asking "anything new?" over and over. It starts as a normal web request that then "upgrades" into this always-open channel, which is why it is the backbone of things like live chat apps, real-time notifications, and collaborative tools where updates need to appear instantly.”

Code Example

A minimal WebSocket echo client in Python
import asyncio
import websockets

async def echo_client():
    uri = "wss://echo.websocket.org"
    async with websockets.connect(uri) as ws:
        # Send a message on the persistent, full-duplex connection
        await ws.send("hello server")
        # Receive without opening a new connection or request
        reply = await ws.recv()
        print("Received:", reply)

asyncio.run(echo_client())

Follow-up Questions

  • How does a WebSocket connection differ from HTTP long-polling?
  • What happens during the WebSocket handshake at the HTTP layer?
  • How would you implement reconnection logic for a dropped WebSocket?
  • Why does WebSocket use a lightweight frame format instead of full HTTP headers per message?

MCQ Practice

1. What HTTP status code confirms a successful WebSocket upgrade?

A 101 Switching Protocols response confirms the server accepted the upgrade to WebSocket.

2. What transport protocol does WebSocket run over?

WebSocket repurposes an existing TCP connection, inheriting TCP's reliable, ordered delivery.

3. What is the main advantage of WebSocket over repeated HTTP polling?

A persistent full-duplex connection avoids the overhead of repeatedly opening new HTTP requests to check for updates.

Flash Cards

How does a WebSocket connection start? β€” As a normal HTTP request with an Upgrade: websocket header, confirmed by a 101 response.

What makes WebSocket β€œfull-duplex”? β€” Either side can send messages at any time without waiting for a request from the other.

What transport does WebSocket use? β€” TCP, inheriting its reliable and ordered delivery.

What must applications add themselves? β€” Heartbeat/ping-pong and reconnect logic, since WebSocket does not handle these automatically.

1 / 4

Continue Learning