• Create Account

Synchronizing server and client time

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

34 replies to this topic

#21smasherprog  Members

568
Like
0Likes
Like

Posted 26 August 2011 - 09:09 AM

Cool. I actually continued to add more to the post above. I have this bad habit of thinking of things after I make a post then adding to the post. I think I did that like 3 times for this one

I do the same thing, ha Just read the rest of it, I have one follow up question though:

So I get that the client time (that is somewhat in sync in with the server) is used when we receive events from the server, but how is it used? To sort the events in the right order? Or is it just used to make better predictions (possibly correct our earlier predictions) ?

Well, yes to both questions. You need to be able to adjust things based on when they occured. For example, you are running in a world and receive a small lag spike for one second where you lose all information sent to you. Once you start receiving all the missed information, you will get things like, player A shot a gun 1020 ms ago and player B started running 1040 ms ago. So now the question becomes, what do you do with this information? The standard way is to play those events, but at a fast speed to catch up to where they should be now. So, all the animations, players speed -- everything runs at for example 3x speed. So, it will take about 300 ms to get events up to where they should be. Its like fast forward on VCRs ( you might not remember them, but I am old enough to!). So, you can use the timestamp to say, " wow, we are 1 second behind the server. I better play this animation really fast to catch up, otherwise I never will." If you are 50ms behind the server, your guess will be very close to exact ( should be very small, like .1 or .2 units max error) on where players are located so you can make small adjustments to a players position over time to correct their positions without speeding anything up.

But the client is synced so that the client can know what to do about information that is received late. You are always going to receive events that have already occurred. The syncing will help you know what type of measures you need to do in order to keep the client running correctly whether it is small adjustments (not noticeable because it is moving a player .1 units over 300 ms) or if the client is lagging badly, running everything at a faster than normal speed to catch up.
Wisdom is knowing when to shut up, so try it.
--Game Development http://nolimitsdesigns.com: Reliable UDP library, Threading library, Math Library, UI Library. Take a look, its all free.

#22hplus0603  Moderators

10569
Like
1Likes
Like

Posted 26 August 2011 - 09:17 AM

I wouldn't have the client send a timestamp to the server.

The reason you send the client timestamp or clock to the server is so that you can measure round trip time, and so that you can adjust offset as appropriate. Also, for certain networking schemes, the timestamp for each event generated on the client is crucial for lag compensation.

O in my formula is the "offset" between client and server time, not the time itself. Thus, I'm assuming a client clock, which (indirectly) determines client timesteps.

timestep = (int)(clock() * StepsPerSecond - Offset)

Client sends "based on my timestep X, the following events happen" (which may be for more than one time step)

Server sends back "I received your timestep X data at my timestep Y" plus whatever other data is pending for the client.

When client gets this data, it measures its own timestep Z. This gives it enough information to figure out which way to adjust the offset. Calculate the "instantaneous" offset as N in the formula above, and adjust the "actual" offset O using the leaky integrator formula.

When starting up, you may want the leaky integrator to be more like 0.9/0.1, and as time goes on, move to 0.99/0.01. This allows you to quickly determine a good match, and then make it more stable once it's established. Or perhaps it's too complex to be worth it. Regarding the adjustments being such that time runs "backwards," I would treat that as a momentary lag on the client, where "nothing happens." If you get a good guess for the offset before you start simulating (from the first client/server handshake, say), and adjust it smoothly, it really shouldn't be a problem.
enum Bool { True, False, FileNotFound };

#23smasherprog  Members

568
Like
0Likes
Like

Posted 26 August 2011 - 09:21 AM

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?
Wisdom is knowing when to shut up, so try it.
--Game Development http://nolimitsdesigns.com: Reliable UDP library, Threading library, Math Library, UI Library. Take a look, its all free.

#24fholm  Members

262
Like
0Likes
Like

Posted 26 August 2011 - 10:20 AM

O in my formula is the "offset" between client and server time, not the time itself. Thus, I'm assuming a client clock, which (indirectly) determines client timesteps.
timestep = (int)(clock() * StepsPerSecond - Offset)
Client sends "based on my timestep X, the following events happen" (which may be for more than one time step)
Server sends back "I received your timestep X data at my timestep Y" plus whatever other data is pending for the client.
When client gets this data, it measures its own timestep Z. This gives it enough information to figure out which way to adjust the offset. Calculate the "instantaneous" offset as N in the formula above, and adjust the "actual" offset O using the leaky integrator formula.

Going to try to break this down into a flow:

• Server starts, incrementing its time step
• Client starts, incrementing its time step, running a different timestep counter then the server, but which will be converted from/to server time using the offset
• Client sends to the server its current timestep (x) with a request
• Server receives requests, responds with its current timestep (y) and also returns the timestep the client sent (x)
• Client receives the server response and measures its current timestep (z) the client then calculates its current offset using this forumula: offsetNew = y - (z - ((z-x) / 2)
• The client then calculates the real offset using the leaky integrator, something like: offset = (offsetOld * 0.95) + (offsetNew * 0.05)

#25fholm  Members

262
Like
0Likes
Like

Posted 26 August 2011 - 10:22 AM

Cool. I actually continued to add more to the post above. I have this bad habit of thinking of things after I make a post then adding to the post. I think I did that like 3 times for this one

I do the same thing, ha Just read the rest of it, I have one follow up question though:

So I get that the client time (that is somewhat in sync in with the server) is used when we receive events from the server, but how is it used? To sort the events in the right order? Or is it just used to make better predictions (possibly correct our earlier predictions) ?

Well, yes to both questions. You need to be able to adjust things based on when they occured. For example, you are running in a world and receive a small lag spike for one second where you lose all information sent to you. Once you start receiving all the missed information, you will get things like, player A shot a gun 1020 ms ago and player B started running 1040 ms ago. So now the question becomes, what do you do with this information? The standard way is to play those events, but at a fast speed to catch up to where they should be now. So, all the animations, players speed -- everything runs at for example 3x speed. So, it will take about 300 ms to get events up to where they should be. Its like fast forward on VCRs ( you might not remember them, but I am old enough to!). So, you can use the timestamp to say, " wow, we are 1 second behind the server. I better play this animation really fast to catch up, otherwise I never will." If you are 50ms behind the server, your guess will be very close to exact ( should be very small, like .1 or .2 units max error) on where players are located so you can make small adjustments to a players position over time to correct their positions without speeding anything up.

But the client is synced so that the client can know what to do about information that is received late. You are always going to receive events that have already occurred. The syncing will help you know what type of measures you need to do in order to keep the client running correctly whether it is small adjustments (not noticeable because it is moving a player .1 units over 300 ms) or if the client is lagging badly, running everything at a faster than normal speed to catch up.

Thanks, now you gave me the whole roundtrip! How to sync, what parts to sync (client to server, not the other way around) and what to use the sync for on the synced part (client). Perfect!

#26hplus0603  Moderators

10569
Like
0Likes
Like

Posted 26 August 2011 - 02:52 PM

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.
enum Bool { True, False, FileNotFound };

#27fholm  Members

262
Like
1Likes
Like

Posted 27 August 2011 - 05:12 AM

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);

#28fholm  Members

262
Like
0Likes
Like

Posted 27 August 2011 - 05:53 AM

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

#29smasherprog  Members

568
Like
0Likes
Like

Posted 27 August 2011 - 08:06 AM

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 ?
Wisdom is knowing when to shut up, so try it.
--Game Development http://nolimitsdesigns.com: Reliable UDP library, Threading library, Math Library, UI Library. Take a look, its all free.

#30fholm  Members

262
Like
0Likes
Like

Posted 27 August 2011 - 10:18 AM

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.

#31hplus0603  Moderators

10569
Like
0Likes
Like

Posted 27 August 2011 - 11:11 AM

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 :-)
enum Bool { True, False, FileNotFound };

#32fholm  Members

262
Like
0Likes
Like

Posted 27 August 2011 - 11:15 AM

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 :-)

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

#33fholm  Members

262
Like
0Likes
Like

Posted 27 August 2011 - 11:38 AM

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 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?

#34hplus0603  Moderators

10569
Like
0Likes
Like

Posted 28 August 2011 - 11:40 AM

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 :-)
enum Bool { True, False, FileNotFound };

#35fholm  Members

262
Like
1Likes
Like

Posted 28 August 2011 - 11:57 AM

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 :-)

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.