===== TCP vs HTTP ===== ==== What is TCP? ==== **TCP (Transmission Control Protocol)** is a transport-layer protocol. It provides a reliable, ordered byte-stream connection between two endpoints (client and server). TCP is like a **pipe** that carries bytes. ==== What is HTTP? ==== **HTTP (Hypertext Transfer Protocol)** is an application-layer protocol. It defines how to format requests and responses (methods like GET/POST, headers, body, status code). HTTP runs **on top of TCP** (most commonly). ==== Key idea ==== * TCP does NOT have “methods”. * HTTP has methods (GET/POST/PUT/DELETE), and those methods are just text/bytes sent through TCP. So the correct mental model is: * **TCP = connection + byte stream** * **HTTP = rules for what bytes mean** ==== Diagram (layering) ==== * Application layer: HTTP (request/response format) * Transport layer: TCP (reliable connection) * Network layer: IP (routing packets) ==== Example: Using TCP for HTTP (manual) ==== You can open a TCP connection and send an HTTP request manually: conn, _ := net.Dial("tcp", "example.com:80") defer conn.Close() fmt.Fprint(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n") io.Copy(os.Stdout, conn) ==== Example: Using HTTP client (recommended) ==== Instead of crafting bytes yourself, use `http.Client`: resp, err := http.Get("http://example.com/") if err != nil { return } defer resp.Body.Close() ==== When to use which ==== * Use **http.Client** when the server speaks HTTP/HTTPS (REST APIs, web, webhooks). * Use **net.Dial** when you need raw TCP for a non-HTTP protocol (Redis/MySQL/custom protocols). ==== Hard words (English) ==== * **transport layer** /ˈtrænspɔːrt ˈleɪər/: tầng vận chuyển * **application layer** /ˌæplɪˈkeɪʃən ˈleɪər/: tầng ứng dụng * **protocol** /ˈproʊtəkɔːl/: giao thức * **byte stream** /baɪt striːm/: luồng byte * **reliable** /rɪˈlaɪəbəl/: đáng tin cậy * **ordered** /ˈɔːrdərd/: đúng thứ tự * **endpoint** /ˈendpɔɪnt/: điểm kết nối (client/server) * **craft** /kræft/: tự “chế”/tự tạo