服务器和客户端之间的同步时钟

时间:2012-02-10 07:57:48

标签: java time client

在我的应用程序中,我有一个服务器和x客户端。客户端启动时,他从服务器获取当前系统时间。每个客户都必须使用服务器时间,不能使用自己的系统时间。

现在我的问题:在客户端上运行时钟的最佳方法是什么,该时钟以当前服务器时间开始并且几乎与其同步运行而不是每隔x秒接收服务器时间? / p>

目标是在客户端显示服务器时间的运行时钟。

客户端时钟可能具有的容差在24小时内约为1秒。

在我的解决方案中,我得到一个定时器,每隔500毫秒触发一次,并在定时器执行时在服务器时间内计数500毫秒。但这不是一个好的解决方案:)因为客户端时钟与服务器时间不同。

感谢您的回复

3 个答案:

答案 0 :(得分:2)

您几乎肯定会使用已建立的时钟同步方法,例如the Network Time Protocol,而不是构建自己的自定义解决方案。它会为您提供比您自己更好的结果,并且您还可以获得所有服务器同意的时间: - )

答案 1 :(得分:2)

我找到了一个适合我情况的解决方案。 我没有使用System.currentTimeMillis(),而是使用System.nanoTime()System.nanoTime()独立于系统时钟。

当我收到当前的服务器时间时,我从系统中保存了额外的ns。然后将使用服务器时间接收的ns时间与当前nanoTime加上服务器时间之间的差值计算当前服务器时间。

示例:

// The Client starts and receive the current Server time and the nanoTime
private long         serverTime = server.getCurrentTime();
private long         systemNano = System.nanoTime();

//To calculate the current Server time without a service call
                                                                        //ns-> ms
long currentServerTime = serverTime + ((System.nanoTime() - systemNano) / 1000000);

THX

答案 2 :(得分:1)

这样做的一种方法是获取服务器时间和本地时间之间的差异,并将其用于时间计算

  • 客户端启动并从服务器获取时间(我将假设使用当前时间,以毫秒为单位,但这可以适应您正在使用的任何时间)
  • 客户端检查其当前系统时间并保存差异
  • 然后可以始终将差异应用于客户端上的当前系统时间以计算服务器时间

示例:

long serverTime = 1328860926471l; // 2012/02/10 10:02, received from wherever
long currentTime = System.currentTimeMillis(); // current client time
long difference = currentTime - serverTime;

// Server time can then me retrieved like this:
long currentServerTime = System.currentTimeMillis() - difference;     
Date serverTimeDate = new Date(currentServerTime);

显然,收到服务器时间后必须保存差异。