Scrapeless Wiki

What Is a WebSocket? – Definition and How It Works

Informational P1 what is a websocket
Overlaps a live page. A published page already targets this keyword: https://www.scrapeless.com/en/blog/websockets. Publishing both risks cannibalisation β€” decide before this goes live.

Learn what a WebSocket is, how the HTTP upgrade handshake works, when persistent bidirectional connections beat polling, and what they cost to operate.

A WebSocket is a persistent, two-way connection between client and server over a single TCP socket. It exists because HTTP's request–response shape is a poor fit for anything the server needs to initiate.

1. What Is a WebSocket?

It is a full-duplex channel established through HTTP and then kept open.

  • Key idea: either side can send at any time, without a request first.
  • Mechanism: an HTTP request upgrades the connection; both then speak the WebSocket frame protocol.
  • Goal: low-latency bidirectional messaging without repeated connection setup.

The URL scheme is ws:// or, over TLS, wss://.

2. The Handshake

A WebSocket starts as an ordinary HTTP request:

GET /socket HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

The server accepts with:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After the 101, HTTP semantics stop. The same TCP connection now carries WebSocket frames in both directions until either side closes it.

Starting as HTTP is deliberate: it means WebSockets traverse the same ports, proxies and firewalls as normal web traffic, which is why they succeeded where earlier protocols did not.

3. Against the Alternatives

Polling Long polling SSE WebSocket
Direction Client pulls Client pulls Server β†’ client Both ways
Connection New each time Held, then reissued One, held One, held
Latency Up to the interval Low Low Low
Overhead Headers every poll Moderate Low Lowest per message
Binary data Yes Yes No, text only Yes
Auto-reconnect N/A Manual Built in Manual
Complexity Trivial Moderate Low Higher

Server-Sent Events are underrated here. If data only flows server-to-client β€” notifications, live figures, progress β€” SSE is simpler, runs over plain HTTP, and reconnects automatically. Reach for WebSockets when you genuinely need the client to send too.

4. Why Polling Is Wasteful

Poll every 5 seconds and each client makes 17,280 requests a day. Nearly all return "nothing new", and each carries full HTTP headers and often a TLS handshake. Meanwhile a change arriving one second after a poll waits four seconds to be seen.

A WebSocket replaces that with one connection and a message when something actually happens: lower latency and dramatically less traffic. The trade is that you now hold state β€” an open connection per client β€” which is the cost polling was buying its way out of.

5. What They Are Used For

  • Chat and messaging, the canonical case.
  • Live financial data, where a second of staleness has a price.
  • Collaborative editing, where every keystroke propagates both ways.
  • Multiplayer games needing continuous low-latency state exchange.
  • Live dashboards and notifications, though SSE often suffices.
  • Browser automation protocols β€” CDP itself runs over a WebSocket, which is how Playwright and Puppeteer talk to Chrome.

6. Operational Realities

  • Connections drop. Networks change, laptops sleep, proxies time out. Reconnection with backoff is your responsibility β€” unlike SSE, nothing does it for you.
  • Idle connections get killed. Many proxies close a socket after 30–120 seconds of silence. Send periodic pings.
  • State is per connection. Scaling horizontally means either sticky routing or a shared pub/sub layer, because the client is attached to one instance.
  • Authenticate at the handshake. Browsers cannot set custom headers on a WebSocket, so tokens usually travel as a query parameter or in a first message β€” and query strings land in logs.
  • Check the origin. WebSockets are not subject to the same-origin policy the way XHR is; a server that ignores Origin is open to cross-site hijacking.
  • Backpressure is real. A slow client with a fast stream will grow a server-side buffer until something fails.

7. Real-World Examples

  • A price ticker pushing updates as trades occur instead of polling per second.
  • A build system streaming logs live as they are produced.
  • Playwright driving Chrome, sending CDP commands and receiving events on one socket.
  • A dashboard rebuilt on SSE after the team realised nothing ever flowed upstream.
  • A "leaking" service whose real problem was clients reconnecting on every drop with no backoff, multiplying connections after each blip.

8. Summary

A WebSocket upgrades an HTTP connection into a persistent, full-duplex channel where either side can send at any time. Beginning as HTTP is what lets it pass through ordinary web infrastructure.

It beats polling on latency and overhead for genuinely real-time, bidirectional workloads. Where data flows only from server to client, Server-Sent Events give most of the benefit with automatic reconnection and far less complexity.

The costs are operational rather than conceptual: reconnection logic, keep-alive pings, per-connection state that complicates horizontal scaling, handshake-time authentication, and origin validation.