中EN

UDP vs. TCP

Markdown2 KB 原始文件

Source: https://gafferongames.com/post/udp_vs_tcp/ Author: Glenn Fiedler | Date: 2008-10-01 | Series: Networking for Game Programmers

Context

For action games (Halo, Battlefield, Quake, Unreal, Counter-Strike, Team Fortress), choosing socket type wrongly ruins multiplayer.

TCP/IP vs IP vs UDP

  • TCP: connection-based, reliable, ordered, stream protocol; breaks data into packets; flow control; easy like file I/O.
  • IP: no connection; packets hop computer to computer; may be lost, duplicated, reordered; self-organizing routing.
  • UDP: thin layer over IP; send datagram to IP:port; unreliable; no ordering; 16-bit checksum insufficient for long high-rate use — add your own.

Typical UDP loss ~1–5%; occasional periods of total loss.

Why TCP fails for time-critical game data

TCP may buffer small writes (Nagle); TCP_NODELAY helps but does not fix head-of-line blocking: lost packet stalls newer data until retransmit (~RTT to 2*RTT+, worse under congestion backoff).

Action games care about most recent input/positions, not what happened a second ago. Waiting for stale resends freezes objects on client and freezes input processing on server; then a clump of packets arrives.

Never use TCP for time-critical data.

Why not mix UDP + TCP

TCP and UDP share IP; TCP congestion behavior can induce UDP loss. Mixing loses control. Prefer implementing needed TCP features inside a custom UDP game protocol. (Using HTTP/REST alongside the game is fine; do not split the game protocol across UDP and TCP.)

Recommendation

Use only UDP for the game protocol. Implement virtual connection, reliability, ordering, congestion avoidance yourself as needed.

引用这一章的笔记

输入关键词开始搜索

滚轮或双指缩放 · 拖动平移 · 双击放大 / 还原