game networking

This is going to be a slightly more ‘abstract’ post compared to what I normally do, but I think it’ll be useful for anyone making multi-player games. The biggest problem with multi-player games is network latency & bandwidth. This is something you just have to design for with your game mechanics, for example many MMOs have ‘cast times’ for most actions to cover the latency between the various clients and the server.

In this post I’m going to show clock synchronisation, a kind of synchronisation where you can ensure your various clients are all sharing the same timestamp as the host, give or take a few ms. For my game, having the same clock on all clients means I can time actions to occur simultaneously across all users. The code below is Java for Android, but it can be ported across to other platforms easily enough.

In this code we first get the client’s current time, we get this as early as possible to minimise the error margin. Next we work out how long it took the packet to arrive from the host – we do this by dividing the total transit time by 2 (the first half was sending the request). Next we work out the difference between the hosts timestamp (with transit time taken into account) and the client’s timestamp.