First step: Time difference between hosts
It assumes that it takes same time for packet to go from server to client and back.
server sends packet with current time to client and client responses back with current time.
After that server has total time. Divide that time on two and you know when packet was on client.
// Server code
int64 dtime = time2 - time1;
int64 dtime2 = dtime / 2;
int64 clientTime = time1 + dtime2;
Second step: Keep track of time difference
Keep track of time difference.
You may calculate moving average for time difference.
float movingExpAvg(float value, float oldValue, float ftime, float time){
float alpha = 1 - expf(-ftime/time);
float r = alpha * value + (1.f - alpha) * oldValue;
return r;
}
Every request from server to client that requires instant response may contain server time and response may contain client time.