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):
- Short Polling: The client periodically sends HTTP requests at fixed intervals. This creates heavy bandwidth overhead and is not truly real-time.
- 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.
- 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.1Host: example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13URI 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 / Aspect | HTTP | WebSocket |
|---|---|---|
| Layer & Transport | Application Layer over TCP | Application Layer over TCP |
| Connection Setup | Standard HTTP Request / Response | HTTP Upgrade Handshake, then persistent framing |
| Communication Model | Unidirectional (Client Request Server Response) | Bi-directional / Full-Duplex (Peer-to-Peer streaming) |
| Data Format | Full HTTP headers + Payload | Lightweight Frames (Minimal overhead) |
| Middlebox/Proxy Routing | Supported via standard intermediaries | Requires direct/transparent TCP connection post-handshake |
| Message Ordering | Dependent on Request/Response sequencing | In-order delivery guaranteed by frame sequencing |