Synchronize time between client/server java sockets

2.8k views Asked by At

Here, I am developing a project with java sockets and I have a problem with the implementation of the correct time synchronization between Server and Client. I am going to describe the problem with a simple example:

Server runs on GMT and keeps a database with various items. Some of those items are on special offer, but these offers have a time limit before they expire.
So let's say that server time now is 9:00AM(GMT) and there is an offer item ending at 10:00AM(GMT).

Client may be on a different time and timezone than the server. So let's say that client time now is 8:00AM(GMT-1), I can take the time and adjust it to client's timezone and find that it ends at 9:00AM(GMT-1) ie in 1 hour.

Problem: How do I calculate the time remaining when a user has a custom time set.
For example, the above client sets the clock manually to be half an hour ahead, ie 8:30AM(GMT-1). If you just do the timezone conversion the item would still be ending at 9:00(GMT-1), so the time left for the offer to finish is wrong (30mins).

One may say that a possible solution would be to set the client to ask the time left in seconds from the server instead of the exact date ending. But I want to implement something like a count down of seconds in the client side. (If offer ends in 60 seconds, the interface would go 60,59,58,..,1,0). So sending a request every second to the server to get the time left is not be network efficient.

One more thing that worries me is that if you do go with the scenario of requesting the "time left in seconds", on slow network the response from server will not come instantly, so by the time the client receives the result is already off time.

2

There are 2 answers

4
WeMakeSoftware On

The simpliest way is not to use client time at all, as it is unreliable.

Just ask the server time periodically. You don't have to do each and every second, but rather before anything important happens (order is made)

0
Error On

you can use NTP protocol. to sync between Server/Client.

NTP standard uses GMT as time reference, and depend on you location you choose the closest ntp pool.

depends on where you are in the world NIST (in us) implements NTP

NTP practically uses stratum server with time source a "cesium clock", with error fraction of nanosecond. used in GPS, money transaction, and your computer probably (if it's unix-like)