Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing client-side and server-side times [duplicate]

I have a webservices that collects realtime market data and displays it in a web frontend.

My frontend (jQuery) needs to display a clock, somewhat synchronized with the server clock (+- a few seconds is fine).

I was thinking of delivering a UTC timestamp alongside the rest of the data the server provides when the client loads.

Then, I would start a timer and every 1 seconds increment the displayed clock.

Is this a good approach or is it better to use a time server?

Thanks!

like image 704
user1094786 Avatar asked Jul 17 '12 11:07

user1094786


1 Answers

You need to account for network latency. Data from your server won't reach you instantly. I suggest doing it using Cristian algorithm:

  1. Client marks current client time (T1) and sends request to server.
  2. Server sends it time (T2) to client.
  3. Client receives server answer and marks its current time again (T3).
  4. T3 - T1 is a total time request needed to go to the server and back (RTT). Now we can assume that going from server to client takes about half of that time. So, your "correct" time is T2 + (T3 - T1)/2

Read more about clock synchronization algorithms on wikipedia

like image 196
Dmitry Osinovskiy Avatar answered Oct 24 '22 13:10

Dmitry Osinovskiy