Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronize time between client/server java sockets

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.

like image 819
javasuns Avatar asked Jun 27 '15 06:06

javasuns


1 Answers

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)

like image 195
WeMakeSoftware Avatar answered Sep 18 '22 05:09

WeMakeSoftware