Networking

From Gamedev.org wiki

Table of contents

Introduction

Networking is a complex beast, and there are a maze of protocols and tricks that you must know about in order to create a proper networked game.

TCP vs UDP

One of the first questions that comes up when devising a networking architecture is whether to go with TCP or UDP in your project.

TCP

  • Pros: Reliable packet delivery (at least as reliable as the Internet is), connection-based protocol which may make more sense and lets you write less code to find out who sent what
  • Cons: Slower than UDP sometimes
  • Suggestion: Use this for games that aren't lag dependent, or crucial game data (for example, scores or player stat updates)

UDP

  • Pros: Fast
  • Cons: Connectionless, so you have to find out who sent what. Packets can arrive in wrong order or not at all.
  • Suggestion: Games where lag is a factor should always use UDP.

Libraries

Now that you know this about networking, you should probably pick an API to work with.

  • HawkNL (http://www.hawksoft.com/hawknl/)
  • SDL_net (http://www.libsdl.org/projects/SDL_net/)

What about HTTP?

The HTTP protocol is extremely handy for things like high scores and some data transfer; some languages like Java support HTTP through native objects. For those of us who aren't so lucky, there are some HTTP libraries:

Do I need threads?

You don't necessarily need threads -- you can use fork and the like. I do recommend using threads, however, and you should either use your language's native threading support, or posix threads (http://www.humanfactor.com/pthreads/) if your language doesn't support threading natively (C, C++).

Lag?

A lot of games deal with perceived lag by using prediction; if it "looks right" on the client side players are much less likely to notice any kind of latency.

Pretty much all action games implement prediction of some kind; one of the simplest algorithms is dead reckoning.

Some problems you'll want to solve with your prediction algorithm:

  • Long lag spikes that diverge your prediction from what the server thinks is happening (causes "warping," "lag misses")
  • Trying to predict abnormal behaviour (donuts, repeated jumps)
  • "Lag cheating" (inducing artificial lag to force the prediction algorithm to reveal enemies)