# Synchronizing server and client time

This topic is 2338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I guess if TCP is used, the roundtriptime can be gathered from the tcpclass.

If UDP is used, then roundtriptime must be calculated, so cant the server and the client calculate the round trip time without the need for timestamps at all?

For example, client send the server packet ID 5 and the client notes its local time. Then, the server acknowledges receipt of the data and sends to the client that the packet was received. Then, the client receives the acknowledgement that the server received ID5. When the client receives this packet, it notes the the received time.
So the round trip time becomes the

roundtriptime = (time when client received acknowledgment of packet ID5) - (time when the client sent out packet ID 5) ;

Also, since the server can calculate the roundtriptime, wouldn't it know by inference what time the client has? For example, if the server knows the roundtriptime is 50 ms, the one way trip should be 25 ms. So, if the server time is 100000 ms, then the clients time would be 25 ms behind the server, correct?

At that point, your "packet id" is your "tick counter." However, at that point, you don't know how much is transmission overhead, and how much is server processing overhead.
In a good system, each side will send "S is my current clock, and your last message was received timestamped your clock Y and my clock C" for each packet.
Thus, when you receive a packet, you can estimate network and processing latency easily when receiving the packet:
ProcessingLatency = S - C
RoundtripLatency = (Now - Y) - (S - C)

If processing and buffering latency doesn't matter (I'm assuming there is a message buffer queue BEFORE packets with timestamps get generated), then you can simplify.

##### Share on other sites
This is my final code, which seems to be working very well:

 using System; using System.IO; using UnityEngine; public static class NetworkTime { public static float offset = 0.0f; public static float gameTime = 0.0f; public static float localTime = 0.0f; public static void UpdateTime() { localTime = Time.time; gameTime = localTime + offset; } public static void UpdateOffset(float remoteTime, float rtt) { var newOffset = (remoteTime - Time.time) + (rtt * 0.5f); if (offset == 0.0f) { offset = newOffset; } else { offset = (offset * 0.95f) + (newOffset * 0.05f); } UpdateTime(); } } 

• Time.time is the current local time this simulation step was started (supplied by Unity as a built in property)
• NetworkTime.UpdateTime is called on both the server and client to set the local time (Time.time isn't used directly anywhere in my code, I always go through NetworkTime.gameTime), the offset will always be 0 on the server so localTime == gameTime on the server. UpdateTime is called at the start of every physics step and frame render to keep the time up to date
• NetworkTime.UpdateOffset is called on the client only, every package that is received from the server has the servers latest gametime as the first four bytes, which is sent into UpdateOffset through the remoteTime paramter. The avarage roundtrip time I get from the lidgren library automatically and is sent in through the rtt parameter. I then use hplus0603's formula (I think, maybe I'll be corrected) to calculate the offset. UpdateOffset also calls UpdateTime as the last thing it does to update the time with the latest offset.
This seems to be working very reliable for me, albeit over only simulated latency so far, but the client seems to be in sync to as close as 5-15ms with the server, which feels good enough for me at least

Slight update: I also calculate the current timestep using a simple calculation like this: timeStep = (int)(gameTime * stepsPerSecond);

##### Share on other sites
I also have a slight follow up question, again

My current sync seems to work pretty well, the client drifts from 5-25ms within the server time, which I feel is good enough. However, this is done on a local connection with simulated latency where server>client and client>server times are very close to identical, so taking round trip timer over two leaves me with a very good estimate. But as we all know these aren't the real world conditions and usually one of the two ways is significantly faster then the other. I know there is no way to deal with this because it's impossible to find out the single trip latency between two connections without doing something like NTP or using a third party, etc.

My question regards this tho: Assume that my round trip time is 100ms, but of this 100ms about 75ms is consumed from the client to the server (which is logical, as most home connections have slower/crappier upload then download) and only 25ms is server>client. Since I use the RTT/2 to calculate my offset between server and client time, a significant drift in this could put me well before the server in terms of timesteps? If my timestep speed is 15ms (66.66Hz) and the split between client>server and server>client on a 100ms connection is 75/25ms then this would put me approximately (100/2 - 25/2) 37.5ms or 2½ timesteps a head of the server.

Now, the problem (in my head) is this: If i always receive events that are "in past time" on the client, don't I need to "fast forward" those? So if I'm 2-3 timesteps a head of the server won't i be receiving events that are (according to my local, estimated gametime on the client) 25ms (server->client) + 50ms (round trip over two) = 75/15 = 5 timesteps in the past. Maybe this isn't a real problem, and since I always will be receiving events that "are in the past" then it's ok, and only if real lag happens and the amount of timesteps I'm "behind" is something like 20+ I need to start "fast forwarding".

Again, thanks for all the help everyone has given me! Hoping this is the last piece of the puzzle

##### Share on other sites
You can find pretty close to the exact time it takes for data to travel between computers (not including their processesing times, by doing what hplus suggested where a client sends a timestamp to the server, and it returns the clients timestamp with one of its own. These timestamps have to be generated as close to when the packets are sent out as possible to minimize any processing that occurs on the computer. However, if you follow that rule, then you should be able to use roundtrip/2 as well. Also, just because typically game servers have good connections, does not mean the path through the internet will be better than your path. The path data takes through the internet is not determined by which ISP you have. A good connection on the game server would be beneficial to you as much as it is for it.

As far as determining the one way time it takes for a packet to travel to or from the server cannot be found out, but only estimated. There are fluctuations in the internet which can cause a packet to take a different path, or perhaps your isp or another node on the path has a small hickup of 15 ms for some reason. There are many small changes that can and do occur for a packet traveling on the internet. You could narrow in on a reasonable approximation however. Through the process of receiving the gameservers time, you would have your guess of the servers time as roundtrip/2 + clienttime. So, when you receive the next gameserver time, you can compare your guess to the servers, if it is consistently off by +50ms, then you could adjust your estimate of the gameservers time by +50. But be carefull, this guess is going to fluctuate up and down by some amount depending on each clients connection. So, perhaps the client could store the last 48 time differences of how off the guess was, average those and then add that onto your guess of the servers time. Then, you can continue to do this for the connection and it should provide the closest you could possibly get to guessing the server time correctly.

Just remember: anything to do with time calculations should be done as soon as possible for the client, and the server should be sending its timestamp as close to when the actual packet leaves as possible to minimize any processing overhead. The time it takes for a packet to leave the computer after you call send() should be less than a ms unless something crazy is going on.

"Edit" are you writing your own reliable UDP network library? If so these time calculations should be happening inside the library automatically, not in the actual game code. What I mean is, as packets are sent and received, your network code should be timestamping certain packets as they leave, and when they are received, processing those timestamps, then passing the data up to your application.

"2nd edit" I see UnitEngine in your code. I think the UnitEngine would have something like this time calculation stuff already built into its network code. Have you checked that out ?

##### Share on other sites

You can find pretty close to the exact time it takes for data to travel between computers (not including their processesing times, by doing what hplus suggested where a client sends a timestamp to the server, and it returns the clients timestamp with one of its own. These timestamps have to be generated as close to when the packets are sent out as possible to minimize any processing that occurs on the computer. However, if you follow that rule, then you should be able to use roundtrip/2 as well. Also, just because typically game servers have good connections, does not mean the path through the internet will be better than your path. The path data takes through the internet is not determined by which ISP you have. A good connection on the game server would be beneficial to you as much as it is for it.

As far as determining the one way time it takes for a packet to travel to or from the server cannot be found out, but only estimated. There are fluctuations in the internet which can cause a packet to take a different path, or perhaps your isp or another node on the path has a small hickup of 15 ms for some reason. There are many small changes that can and do occur for a packet traveling on the internet. You could narrow in on a reasonable approximation however. Through the process of receiving the gameservers time, you would have your guess of the servers time as roundtrip/2 + clienttime. So, when you receive the next gameserver time, you can compare your guess to the servers, if it is consistently off by +50ms, then you could adjust your estimate of the gameservers time by +50. But be carefull, this guess is going to fluctuate up and down by some amount depending on each clients connection. So, perhaps the client could store the last 48 time differences of how off the guess was, average those and then add that onto your guess of the servers time. Then, you can continue to do this for the connection and it should provide the closest you could possibly get to guessing the server time correctly.

Just remember: anything to do with time calculations should be done as soon as possible for the client, and the server should be sending its timestamp as close to when the actual packet leaves as possible to minimize any processing overhead. The time it takes for a packet to leave the computer after you call send() should be less than a ms unless something crazy is going on.

"Edit" are you writing your own reliable UDP network library? If so these time calculations should be happening inside the library automatically, not in the actual game code. What I mean is, as packets are sent and received, your network code should be timestamping certain packets as they leave, and when they are received, processing those timestamps, then passing the data up to your application.

"2nd edit" I see UnitEngine in your code. I think the UnitEngine would have something like this time calculation stuff already built into its network code. Have you checked that out ?

Hey, I'm using the Lidgren networking library (C# UDP library, it's very solid). Lidgren already has a roundtrip time mechanism built in, which seems to be really accurate so I just take this number and divide over two to get the one way time, and it seems to be pretty accurate (with simulated latency it's hovering around 5-10ms difference between client and server, tops).

What you've described is pretty much what I do: I use the algorithm hplus0603 showed, it's just that the roundtrip time is automatically calculated for me by the networking library I use, so there is no need for me to send manual timestamps back and forth between the server and client.

My question was regarding the fact that I'm always going to be receiving events in the "past", as my game time is synced up with the server (very closely), and you talked earlier about "fast forwarding" when receiving events "from the past", but really that should only happen if they are a lot in the past?

Edit: And yes I use Unity for the graphics, but the unity networking is really dodgy and slightly awkward (and has been riddled with bugs over the past year or so) to use so I've opted for using a custom library and custom networking code.

##### Share on other sites

My question regards this tho: Assume that my round trip time is 100ms, but of this 100ms about 75ms is consumed from the client to the server (which is logical, as most home connections have slower/crappier upload then download)

What you care about is ordering all events in a strictly increasing sequence, not the specific sync to the server. It doesn't matter how the latency is distributed.

Also, your assumption that upload bandwidth matters for client latency isn't really true. Let's do some math, assuming a cable connection with really good downstream and really constrained upstream:

User upload == 20 kB / sec
Client command packet to server == 300 bytes
Server update packet to client == 3000 bytes

So, one packet takes 300 bytes / 20 kB == 15 milliseconds to transmit up, for the first hop (from the client). Note that, if the command packet is smaller, this number changes significantly!
One packet down takes 3000 bytes / 1 MB == 3 milliseconds to transmit down, for the last hop (to the client).
However, as soon as you're outside of the client connection, you're on a routed internet infrastructure, where upload and download throughputs are usually symmetric, and always aggregated among many consumer, and thus a lot faster. At that point, it's the actual speed of electrons in copper (about 2/3 the speed of light) and the routing latency that matters, not the client bandwidth limitations.
Thus, any amount of your latency greater than (15+3) == 18 milliseconds in this case will be evenly divided between "up" and "back," so the maximum you'll be off in your estimate would be (15-3) == 12 milliseconds;

But, as I said, as long as you have a strict ordering of events, all of that doesn't matter much :-)

##### Share on other sites

[quote name='fholm' timestamp='1314446018' post='4854389']
My question regards this tho: Assume that my round trip time is 100ms, but of this 100ms about 75ms is consumed from the client to the server (which is logical, as most home connections have slower/crappier upload then download)

What you care about is ordering all events in a strictly increasing sequence, not the specific sync to the server. It doesn't matter how the latency is distributed.

Also, your assumption that upload bandwidth matters for client latency isn't really true. Let's do some math, assuming a cable connection with really good downstream and really constrained upstream:

User upload == 20 kB / sec
Client command packet to server == 300 bytes
Server update packet to client == 3000 bytes

So, one packet takes 300 bytes / 20 kB == 15 milliseconds to transmit up, for the first hop (from the client). Note that, if the command packet is smaller, this number changes significantly!
One packet down takes 3000 bytes / 1 MB == 3 milliseconds to transmit down, for the last hop (to the client).
However, as soon as you're outside of the client connection, you're on a routed internet infrastructure, where upload and download throughputs are usually symmetric, and always aggregated among many consumer, and thus a lot faster. At that point, it's the actual speed of electrons in copper (about 2/3 the speed of light) and the routing latency that matters, not the client bandwidth limitations.
Thus, any amount of your latency greater than (15+3) == 18 milliseconds in this case will be evenly divided between "up" and "back," so the maximum you'll be off in your estimate would be (15-3) == 12 milliseconds;

But, as I said, as long as you have a strict ordering of events, all of that doesn't matter much :-)
[/quote]

Thanks, again! So you're saying that getting an incredibly correct sync is not terribly important, as long as it's "somewhat" in sync, say -50 to +50ms of the server it's good enough? And yes you are right about the download/upload

##### Share on other sites
I've also read the two papers/articles on half life engine lag compensation again, seeing this at the end:

It is assumed in this paper that the client clock is directly synchronized to the server clock modulo the latency of the connection. In other words, the server sends the client, in each update, the value of the server's clock and the client adopts that value as its clock.[/quote]

Quote from: http://developer.val...mization#fnote6

I interpret this as that half life doesn't "add" the roundtrip/2 to the time received by the server, it just lets the client run the same clock as the server, somewhat in the past (server->client transit time) and that's it. Honestly this feels like a much more clear cut option (especially when implementing the type of lag compensation that is explained in the same article). Or am I missing something, again?

##### Share on other sites

I interpret this as that half life doesn't "add" the roundtrip/2 to the time received by the server, it just lets the client run the same clock as the server, somewhat in the past (server->client transit time) and that's it. Honestly this feels like a much more clear cut option (especially when implementing the type of lag compensation that is explained in the same article). Or am I missing something, again?

So, again: The goal is to make everyone affect the world (execute events) in the same order. As long as that happens, the particular values of the clocks may not matter at all! It's entirely up to your specific networking and simulation model, exactly what you put where.
For example, I've worked on a system where user-controlled objects are run at "server clock plus upstream delay" and remote-controlled objects are run at "server clock minus downstream delay" which ends up with things like the avatar's upper body being run ahead of time (because you can aim a weapon) but the lower body being run after time (because it's slaved to a vehicle driven by someone else).
So, if at this point, you have a system that works, then I suggest you keep it that way until there's evidence that you need to change it :-)

##### Share on other sites
[quote name='hplus0603']So, if at this point, you have a system that works, then I suggest you keep it that way until there's evidence that you need to change it :-)[/quote]

Thanks for all your help, and this was probably the best advice I got in this thread. I got something that works, I need to stop over-thinking it