767 words
4 minutes
Sockets and WebSocket Explained

What Is a Socket?#

To understand sockets, it helps to distinguish three key networking components:

  • TCP/IP (Transport Layer): Handles how data is transported across the network.
  • HTTP (Application Layer): Handles how data is packaged and structured so applications can interpret it.
  • Socket (API Layer): Acts as a programming interface that wraps the TCP/IP suite, exposing functions for developers to communicate over the network.

While TCP/IP handles transport, transmitting raw bytes without an Application Layer protocol leaves the receiving end unable to interpret the payload’s meaning. Structured protocols like HTTP, FTP, or TELNET (as well as custom application protocols) give that raw data context. For example, Web applications package text and resources using HTTP, then rely on TCP/IP to transport those payloads over the wire.

A Socket is not a protocol itself; it is an abstraction API. Just as an operating system exposes standard APIs (like Win32) to interact with underlying kernel features, TCP/IP relies on Socket APIs to let developers build network applications programmatically.

+-------------------------------------------------------+
| Application Layer |
| HTTP / FTP / TELNET / Custom App Protocols |
+--------------------------+----------------------------+
|
v
+-------------------------------------------------------+
| Socket API |
| (Programming Interface wrapping Transport Layer) |
+--------------------------+----------------------------+
|
v
+-------------------------------------------------------+
| Transport Layer |
| TCP / IP |
+-------------------------------------------------------+

WebSocket Protocol#

Origins & Motivation#

WebSocket originated as part of the WHATWG Web Applications specification (HTML5). Around 2008, engineers sought a native full-duplex connection for the Web, initially referencing it as TCPConnection.

Existing workaround techniques on top of HTTP—such as polling and long-polling—failed to deliver efficient, low-latency, real-time interaction. The opening section of the WebSocket RFC explicitly states its purpose: to eliminate the continuous overhead of multiple HTTP requests and long-polling when browser applications need real-time data streaming.

Socket vs. WebSocket Despite their similar names, standard network Sockets and WebSockets are distinct concepts. A standard Socket is an operating system API for TCP/IP communications, whereas WebSocket is a specific Application Layer protocol built for web browsers and servers.

Why Use WebSocket?#

The primary goal of WebSocket is to enable true bi-directional, real-time communication.

While HTTP/1.1 introduced persistent connections to pipeline multiple request/response pairs over a single TCP connection, its core interaction model remains strictly unidirectional (one request triggers one response).

Before WebSocket, developers used three main workarounds for bi-directional communication (such as chat systems):

  1. Short Polling: The client periodically sends HTTP requests at fixed intervals. This creates heavy bandwidth overhead and is not truly real-time.
  2. Long Polling: The client sends an HTTP request with a long timeout, and the server holds the connection open until new data is available. This reduces unnecessary requests compared to short polling, but still incurs HTTP header overhead on every update.
  3. HTTP Keep-Alive vs. TCP Long Connection: HTTP persistent connections (“Keep-Alive”) still operate on a request/response basis, leading to high latency and redundant overhead. In contrast, raw TCP sockets (or WebSockets) maintain a continuous, open channel where both sides can stream messages instantly without re-sending HTTP headers.

How WebSocket Works#

WebSocket replaces traditional HTTP for bi-directional streaming, while piggybacking on existing HTTP infrastructure (using default ports 80 and 443) to ensure compatibility with existing proxies, firewalls, and network middleboxes.

The protocol consists of two phases: Handshake and Data Transfer.

1. Handshake Phase#

The handshake initiates via a standard HTTP GET request. The client requests a protocol upgrade, and if accepted, the server switches the underlying TCP connection from HTTP to WebSocket.

Key Handshake Request Headers#

  • Upgrade: websocket — Requests upgrading the existing TCP connection to the WebSocket application protocol.
  • Connection: Upgrade — Indicates that the connection headers should be processed for protocol transition.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

URI Scheme Syntax#

ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]

2. Data Transfer Phase#

Once the server returns an HTTP 101 Switching Protocols response, the WebSocket connection transitions to the OPEN state.

  • Framing: Data is sent using lightweight binary or text frames rather than HTTP request/response payloads.
  • Masking: All frames sent from client to server must be masked to prevent proxy cache poisoning. Frames sent from server to client must not be masked. Unmasked client frames trigger immediate connection termination via a Close frame.
  • Frame Structure: Each frame contains an opcode (defining frame type, e.g., text, binary, ping, pong, close), payload length, and the frame payload (which includes extension data and application payload).

Comparison: WebSocket vs. HTTP#

Feature / AspectHTTPWebSocket
Layer & TransportApplication Layer over TCPApplication Layer over TCP
Connection SetupStandard HTTP Request / ResponseHTTP Upgrade Handshake, then persistent framing
Communication ModelUnidirectional (Client Request →\rightarrow Server Response)Bi-directional / Full-Duplex (Peer-to-Peer streaming)
Data FormatFull HTTP headers + PayloadLightweight Frames (Minimal overhead)
Middlebox/Proxy RoutingSupported via standard intermediariesRequires direct/transparent TCP connection post-handshake
Message OrderingDependent on Request/Response sequencingIn-order delivery guaranteed by frame sequencing
Sockets and WebSocket Explained
https://astro-nyc.pages.dev/posts/sockets-and-websocket-explained/
Author
Hari
Published at
2026-08-24
License
CC BY-NC-SA 4.0