Networking & Sockets

TCP versus UDP

/ TCP -> TEE-CEE-PEE, UDP -> YOO-DEE-PEE /

There are two ways to send something across town. You can phone someone: you dial, they pick up, you have a two-way line where everything you say arrives in order and nothing is lost, and at the end you hang up. Or you can throw a postcard in a mailbox: no setup, no guarantee it arrives, no guarantee postcards arrive in the order you sent them, but it is fast and cheap. TCP is the phone call; UDP is the postcard. Both ride on top of IP, which itself is just unreliable postcards.

TCP (Transmission Control Protocol) is connection-oriented and reliable: the two sides first establish a connection, then exchange an ordered, gap-free stream of bytes. If a piece is lost in transit, TCP detects it and resends; if pieces arrive out of order, TCP reorders them; it also slows down when the network is congested. You get the comforting illusion of a clean pipe between the two programs. UDP (User Datagram Protocol) is connectionless and best-effort: you hand it a datagram (a self-contained chunk of bytes) addressed to an IP and port, and it tries once to deliver it. Datagrams may be lost, duplicated, or arrive in a different order, and UDP will not tell you - but it adds almost no overhead and no waiting.

Why it matters: the choice shapes everything above it. Use TCP when correctness matters and a little delay is fine - web pages, files, email, ssh. Use UDP when speed and low latency beat completeness, and you will handle loss yourself - live video, games, DNS lookups. A common honesty point: TCP's 'reliable' means delivered-or-the-connection-breaks, not 'instant' and not 'cannot fail'; and TCP gives you a byte stream with no message boundaries, while UDP preserves each datagram as one unit.

Loading a web page uses TCP - you want every byte of the page, in order, even if it takes a moment longer. A video call uses UDP - if one frame is lost it is better to skip it and show the next live frame than to freeze the call waiting for old data.

TCP = reliable ordered phone call; UDP = fast best-effort postcards. Same IP underneath both.

TCP being reliable does not make it secure or private - the bytes are still readable on the wire unless you add encryption (TLS, covered later). Reliability and security are separate concerns.

Also called
Transmission Control ProtocolUser Datagram Protocol傳輸控制協定使用者資料包協定