A Simplified Understanding of TCP, HTTP, SSE, and WebSocket

Features
TCP
HTTP
SSE
WebSocket
Communication Direction
Bidirectional
Request-Response
Unidirectional (Server → Client)
Bidirectional
Underlying Protocol
IP
TCP
HTTP
TCP (Initial handshake is HTTP)
Protocol Layer
Transport Layer
Application Layer
Application Layer
Application Layer
Core Advantages
Reliable, Stable
Simple, Stateless, General
Lightweight, Auto-Reconnect
True Duplex, Low Latency
Main Disadvantages
Complex Protocol, High Overhead
Header Redundancy, Stateless
Unidirectional Communication
Requires Dedicated Server Support
Applicable Scenarios
Most Network Application Foundations
Web Browsing, API Calls
Message Notifications, Status Updates
Instant Messaging, Online Gaming

TCP

  • Communication Direction:

    • Bidirectional Communication: Once a connection is established through the “three-way handshake”, data can be transmitted simultaneously in both directions.

  • Execution Principle:

  1. Three-Way Handshake: The client and server establish a reliable connection through three exchanges of information.

  2. Data Transmission: Data is divided into segments for transmission, each segment has a sequence number.

  3. Reliability Assurance: Through mechanisms such as sequence numbers, acknowledgment (ACK), timeout retransmission, and flow control (sliding window), it ensures that data is error-free, not lost, not duplicated, and arrives in order.

  4. Four-Way Handshake: After communication ends, the connection is gracefully closed through four exchanges of information.

  • Core Advantages:

    • Reliable and Stable: Ensures ordered and complete delivery of data, which is the foundation for most applications requiring high reliability.

    • Flow Control and Congestion Control: Can dynamically adjust the sending rate based on network conditions to prevent network congestion.

    • Resource Consumption:

      • High: To ensure reliability, TCP has a lot of header information and needs to maintain connection states (like sequence numbers, window sizes), resulting in relatively high overhead.

    • Disadvantages:

      • High Overhead: Header overhead and the acknowledgment and retransmission mechanisms required to ensure reliability lead to relatively low transmission efficiency.

      • Slow Connection Establishment: Each connection establishment requires three-way handshake, which incurs latency.

    • Applicable Scenarios:

      • Suitable for scenarios that require high data integrity and order, such as file transfer (FTP), email (SMTP), and as the foundation for HTTP and WebSocket.

    HTTP

    • Communication Direction:

      • Request-Response Model: Communication is always initiated by the client, and the server responds. The server cannot actively push information to the client.

    • Execution Principle:

    1. The client establishes a TCP connection with the server.

    2. The client sends an HTTP request message to the server (including request line, request headers, request body).

    3. After receiving the request, the server processes it and returns an HTTP response message (including status line, response headers, response body).

    4. The connection is closed (HTTP/1.0) or kept for a while (HTTP/1.1 Keep-Alive).

  • Core Advantages:

    • Simple and Flexible: The protocol itself is simple, easy to understand and implement.

    • Stateless: The server does not save the client’s connection state, reducing the burden on the server and facilitating scalability.

    • Strong Generality: Widely supported by all browsers and servers, it is the de facto standard for internet applications.

    • Resource Consumption:

      • Relatively High (Especially HTTP/1.1): Each request carries a complete HTTP header, resulting in a lot of redundant information. To handle concurrent requests, browsers establish multiple TCP connections, consuming resources.

    • Disadvantages:

      • Stateless: In scenarios that require state maintenance (like shopping carts), it requires the use of Cookie/Session mechanisms, increasing complexity.

      • Head-of-Line Blocking (HTTP/1.1): A connection can only handle one request at a time, subsequent requests must wait for the previous request to complete.

      • Unidirectionality: Can only be initiated by the client, not suitable for scenarios requiring real-time server push.

    • Applicable Scenarios:

      • Web page browsing, RESTful API calls, resource downloads, and most web applications.

    • Important Supplement: The Evolution of HTTP/2

      • HTTP/2 greatly enhances performance by introducingBinary Framing,Multiplexing (handling multiple requests simultaneously over a single TCP connection, solving the head-of-line blocking issue),Header Compression, andServer Push. This makes HTTP/2 far more efficient than HTTP/1.1.

    SSE

    • Communication Direction:

      • Unidirectional: Can only send data from the server to the client.

    • Execution Principle:

    1. The client initiates an HTTP request to the server using the JavaScript EventSource object.

    2. After receiving the request, the server responds with a header containing Content-Type: text/event-stream, and keeps the connection open.

    3. The server can send text event streams to the client at any time through this open connection in a specific format (e.g., data: message\n\n).

    4. The client receives and processes data by listening to events like onmessage.

  • Core Advantages:

    • Simple Implementation: Based on standard HTTP, the client API is simple, and backend implementation is relatively easy.

    • Lightweight and Efficient: Compared to WebSocket, the protocol is simpler and has less overhead.

    • Auto-Reconnect: The browser natively supports automatic reconnection and can carry the last event ID to ensure data continuity.

    • Resource Consumption:

      • Relatively Low: Built on a single HTTP connection, the protocol has low overhead.

    • Disadvantages:

      • Unidirectional Communication: The client cannot send messages to the server through this connection; if interaction is needed, a new HTTP request must be initiated.

      • Data Format Limitations: Can only send UTF-8 encoded text data, does not support binary.

    • Applicable Scenarios:

      • Scenarios requiring the server to push information unidirectionally to the client, such as stock price updates, news pushes, online status updates, and ChatGPT’s streaming text output.

    WebSocket

    • Communication Direction:

      • Bidirectional Communication (Full Duplex): Once the connection is established, both the client and server can send data to each other at any time and simultaneously.

    • Underlying Protocol:

      • TCP. It initially uses the HTTP/HTTPS protocol for a “handshake” and then upgrades the protocol to WebSocket.

    • Execution Principle:

    1. The client initiates a special HTTP request with headers containing Upgrade: websocket, etc.

    2. If the server supports it, it will return a 101 status code, agreeing to the protocol upgrade.

    3. After that, communication on this TCP connection follows the WebSocket protocol, independent of HTTP.

    4. Both parties can freely send text or binary data frames until one party closes the connection.

  • Core Advantages:

    • True Bidirectional Communication: Extremely low latency, very suitable for real-time interactive applications.

    • Small Header Overhead: After a successful handshake, the header of data frames is very small (usually only 2-10 bytes), resulting in minimal transmission overhead.

    • No Cross-Origin Restrictions: The WebSocket protocol itself does not have the same-origin policy restrictions.

    • Resource Consumption:

      • Low After Connection Establishment: Small header overhead. However, maintaining a persistent TCP connection consumes some server resources.

    • Disadvantages:

      • Implementation is Slightly Complex: Requires dedicated server-side support and management of connection states.

      • Compatibility: Some older network proxies or firewalls may not support the WebSocket protocol.

      • No Automatic Reconnect: After disconnection, the application layer needs to implement reconnection logic itself.

    • Applicable Scenarios:

      • Scenarios requiring high real-time, bidirectional interaction, such as online chat rooms, real-time collaborative editing, online multiplayer games, and real-time data monitoring dashboards.

    Some Previous Questions:

    1. Why is TCP considered full duplex?

    2. Why does HTTP operate as unidirectional communication?

    3. How does SSE create the illusion of bidirectional communication through HTTP?

    4. What is the WebSocket protocol, and why does it need to borrow HTTP for protocol upgrades? Is WebSocket essentially still TCP?

    Leave a Comment