Sockets & Network Programming

the byte-stream abstraction

Imagine pouring water from one cup into another through a hose. You might pour in three separate splashes, but at the far end the water comes out as one continuous flow — there is no way to tell where one splash ended and the next began. A TCP connection delivers your data exactly like that: as one continuous, ordered stream of bytes, with no built-in marks separating the chunks you sent.

Concretely, when your program calls send three times — say 100 bytes, then 50, then 30 — TCP does not promise the receiver gets three reads of 100, 50, and 30. The kernel may merge them and deliver all 180 bytes in a single recv, or split them across several recv calls, depending on timing, buffering, network conditions, and Nagle's algorithm. All TCP guarantees is that every byte arrives exactly once, in the order you sent it. It is reliable and ordered, but it has no concept of a 'message' — the boundaries between your application's logical units are invisible to it. UDP is the opposite: it preserves message boundaries because each datagram is delivered as one unit.

Why it matters: this single fact is behind a huge fraction of network programming bugs. Because TCP is just a byte stream, any application that exchanges discrete messages — a chat protocol, a database wire protocol, HTTP itself — must add its own message framing on top, using length prefixes or delimiters, so the receiver knows where each message starts and stops. Beginners who assume 'one send equals one recv' write code that works on localhost (where data rarely gets split) and then mysteriously breaks under real network load.

A client sends two chat lines back to back: "hello\n" then "world\n". The server's single recv may return "hello\nworld\n" all at once, or even "hel" then "lo\nworld\n". Only the \n delimiters let the server split them back into two messages.

TCP guarantees order, not message boundaries — you must add those.

The deadly assumption: 'one send produces one recv.' It does not. TCP can merge or split your writes freely. Code that ignores this often passes local tests and fails in production.

Also called
byte streamstream of bytesTCP byte stream位元組串流字節流