Lesson 1.2: Network Fundamentals for Game Developers
Welcome to Lesson 2! Now that you understand the high-level architectures, it's time to look under the hood. In this lesson, we'll explore the fundamental networking concepts you need to know: the OSI model, transport protocols (TCP vs. UDP), sockets, NAT traversal, and Round-Trip Time (RTT). Understanding how data actually moves is essential for building responsive online games.
Learning Objectives
TIP
By the end of this lesson, you will be able to:
- Explain the OSI model layers relevant to game networking.
- Compare TCP and UDP and determine when to use each.
- Describe how sockets work at the programming level.
- Understand NAT traversal challenges and solutions.
- Measure and interpret Round-Trip Time (RTT) and jitter.
1. The OSI Model — A Roadmap for Network Communication
The Open Systems Interconnection (OSI) model is a conceptual framework that divides network communication into seven layers. As game developers, we don't need to memorize every layer, but we do need to understand where we have control—and where the network can surprise us.
Layer 7 – Application (your game code)
Layer 6 – Presentation (encoding, encryption)
Layer 5 – Session (connection management)
Layer 4 – Transport (TCP, UDP)
Layer 3 – Network (IP, routing)
Layer 2 – Data Link (Ethernet, Wi-Fi)
Layer 1 – Physical (cables, radio)- Layer 7 (Application): This is where your game logic lives. You decide what messages to send and when.
- Layer 4 (Transport): You choose TCP or UDP. This layer handles reliability, ordering, and port numbers.
- Layer 3 (Network): IP addresses and routing. You have limited control here—it's the internet's infrastructure.
- Layers 1 & 2: The physical medium. Wi-Fi, mobile networks, and cables all introduce different latency and loss characteristics.
TIP
For game developers, the critical choice is at Layer 4: TCP or UDP.
2. TCP vs. UDP — The Eternal Choice
Transmission Control Protocol (TCP)
TCP is a connection-oriented, reliable, ordered stream protocol. It guarantees that every byte you send arrives intact and in the correct order. If a packet is lost, TCP automatically retransmits it.
How it works:
TCP establishes a connection (the three-way handshake) and then sends data as a continuous stream. Under the hood, it segments the stream into packets, numbers them, and waits for acknowledgments. If an acknowledgment is missing, it resends.
| Aspect | Description |
|---|---|
| Pros | No packet loss — data is guaranteed |
| Automatic retransmission and ordering | |
| Widely supported and easy to use | |
| Cons | Head-of-line blocking: If a packet is lost, all later packets are held in a buffer until the lost one is retransmitted |
| Higher overhead per packet | |
| Not ideal for real-time action where the latest state matters more than every single packet |
User Datagram Protocol (UDP)
UDP is connectionless, unreliable, and unordered. You send datagrams (packets) to an IP address and port, and they may arrive, may arrive out of order, or may be dropped entirely. There is no built-in acknowledgment or retransmission.
| Aspect | Description |
|---|---|
| Pros | Low latency — no head-of-line blocking |
| You control reliability and ordering at the application level | |
| Minimal overhead | |
| Cons | No guarantees — you must implement your own reliability if needed |
| More complex to program |
When to Use Which
| Game Type | Typical Transport |
|---|---|
| Real-time action (FPS, fighting, racing) | UDP for gameplay; TCP for chat, matchmaking |
| Turn-based, card games | TCP (simpler, loss-free) |
| MMOs | UDP for movement/combat; TCP for inventory, chat |
| Web games (WebGL) | WebSocket (TCP-based) or WebRTC (UDP-based) |
TIP
Many games use a hybrid approach: UDP for time-sensitive data (player inputs, positions), and TCP for reliable data (chat, login, purchases).
3. Sockets — The Programming Interface
A socket is the software endpoint that your game uses to send and receive data over the network. Think of it as a door: you open it, bind it to a port, and then data flows through it.
Creating a UDP Socket (C# Example)
// Create a UDP socket
using System.Net;
using System.Net.Sockets;
Socket udpSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
// Bind to a port (e.g., 7777) so the OS knows where to deliver packets
udpSocket.Bind(new IPEndPoint(IPAddress.Any, 7777));
// Send data to a remote endpoint
IPEndPoint remote = new IPEndPoint(IPAddress.Parse("192.168.1.5"), 7778);
byte[] data = Encoding.UTF8.GetBytes("Hello, world!");
udpSocket.SendTo(data, remote);
// Receive data (blocking)
byte[] buffer = new byte[1024];
EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
int received = udpSocket.ReceiveFrom(buffer, ref sender);With UDP, you send discrete datagrams. With TCP, you'd use SocketType.Stream and ProtocolType.Tcp, and then Send()/Receive() on a connected stream.
Ports and IP Addresses
- IP address: Identifies a machine on the network (e.g.,
203.0.113.42). - Port: Identifies a specific process or service on that machine (e.g., 7777). Ports allow multiple networked applications to coexist.
When a game client connects to a server, it needs the server's public IP and port. The client itself uses a random ephemeral port (usually assigned by the OS).
4. NAT Traversal — The Hidden Obstacle
Network Address Translation (NAT) is how routers allow multiple devices on a local network to share a single public IP address. Without NAT, your home router would need a unique public IP for every device—impossible with IPv4.
NAT is essential, but it creates a problem for peer-to-peer games: two players behind different routers cannot easily initiate direct connections because neither router knows how to forward packets to the correct internal device.
Common NAT Traversal Techniques
- Port Forwarding (Manual): Players configure their router to forward a specific port to their computer. Works but is user-unfriendly.
- UPnP (Universal Plug and Play): Routers that support UPnP allow applications to request a port mapping automatically. Many games use this for listen servers.
- STUN (Session Traversal Utilities for NAT): A server helps discover the public IP and port mapping. Used in WebRTC and many P2P games.
- TURN (Traversal Using Relays around NAT): When direct connection fails, relay all traffic through a server. Adds latency but works everywhere.
- Hole Punching: Both clients send packets to each other's predicted public endpoints simultaneously, creating a temporary opening in the NAT.
INFO
For client-server games, NAT is less of an issue: the server has a public IP and clients initiate connections to it. The server doesn't need to initiate connections to clients.
5. Round-Trip Time (RTT) — The Pulse of Latency
Round-Trip Time (RTT) is the time it takes for a packet to travel from your client to the server and back. It's the single most important metric for network performance in games.
| RTT Range | Feel |
|---|---|
| Low (< 30 ms) | Feels instantaneous. Competitive games strive for this. |
| Medium (30–100 ms) | Noticeable but playable with compensation techniques. |
| High (> 100 ms) | Lag becomes apparent. Actions feel delayed. |
RTT is affected by:
- Physical distance (speed of light limits)
- Routing (how many hops and how congested)
- Network technology (fiber vs. cable vs. mobile)
Measuring RTT
Games typically measure RTT by sending a "ping" packet (often with a timestamp) and calculating the difference when the echo returns. This is why you see "ping" displayed in many games.
RTT vs. Jitter
Jitter is the variation in RTT over time. High jitter is often worse than consistent high latency because it makes prediction and compensation difficult.
TIP
Always monitor both RTT and jitter. A stable 80ms connection feels better than a variable 40-120ms connection.
Hands-On Tasks
Task 1: Measure Your Network
- Open a terminal or command prompt.
- Run
ping google.comand observe the RTT. - Run
ping -n 20 google.comto see average RTT over multiple packets.
Task 2: Analyze Packet Loss
- Run
ping -f -l 1472 google.com(Windows) to test the maximum packet size before fragmentation. - Note any packet loss and how it affects the reported RTT.
Task 3: Build a Simple UDP Chat
- Write a minimal UDP chat program in C#, Python, or your language of choice.
- Run two instances on the same machine (using different ports).
- Send messages back and forth and observe:
- Can packets be dropped?
- Can packets arrive out of order?
Task 4: Capture Network Traffic
- Download and install Wireshark.
- Play a few minutes of an online game.
- In Wireshark, filter by UDP and observe the packet flow.
Summary
Key Takeaways
- TCP gives you reliability and ordering at the cost of potential head-of-line blocking. Use it for non-critical or transactional data.
- UDP gives you speed and flexibility. Use it for real-time gameplay and implement reliability only where needed.
- Sockets are your direct interface to the network. Understanding them is essential for low-level control.
- NAT complicates peer-to-peer connections. For client-server games, the problem is minimized.
- RTT and jitter are the metrics that define player experience. Compensation techniques start with measuring these accurately.
Check Your Understanding
- Why is head-of-line blocking a problem for real-time games using TCP?
- What is the difference between STUN and TURN servers?
- Why might a game use both TCP and UDP simultaneously?
- What is jitter, and why is it important for networked games?
- How does NAT affect peer-to-peer game connections?
Click to see answers
- Head-of-line blocking occurs when a lost packet delays all subsequent packets until retransmission completes, causing sudden lag spikes in games.
- STUN helps clients discover their public IP and port mapping for direct connections. TURN relays all traffic through a server when direct connection isn't possible.
- Real-time data (player positions, inputs) uses UDP for low latency, while reliable data (chat, login, inventory) uses TCP.
- Jitter is variation in RTT over time. High jitter makes prediction difficult and can cause erratic game behavior even if average latency is acceptable.
- NAT creates a problem because two players behind different routers can't easily initiate direct connections—the router doesn't know how to forward packets to the correct internal device.
Additional Resources
Next Up
In the next lesson, we'll explore the game loop and network threading—how to integrate networking without stuttering your game's frame rate. We'll cover fixed timestep vs. variable timestep and decoupling network operations from rendering!