在我的应用程序中,我有一个服务器和x客户机。当客户端启动时,他从服务器获得当前系统时间。每个客户端都必须使用服务器时间,不能使用自己的系统时间。
现在我的问题:,在客户机上运行时钟的最好方法是从当前服务器时间开始,并与它几乎同步运行,而不需要每x秒钟接收服务器时间一次?
目标是在客户机上显示一个运行服务器时间的运行时钟。
客户端时钟可能具有的公差大约是24小时内的1秒。
在我的解决方案中,我得到了一个计时器,它每500 my触发一次,当计时器执行时,在服务器上计数500 my。但这不是一个好的解决方案:)因为客户端时钟与服务器时间不同。
谢谢你的答复
发布于 2012-02-13 07:25:23
我找到了一个非常适合我的情况的解决方案。我使用的不是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
发布于 2012-02-10 08:36:16
您几乎可以肯定地使用已建立的时钟同步方法(如网络时间协议 ),而不是构建您自己的自定义解决方案。它将为您提供比您自己更好的结果,并且您还有一个额外的好处,就是您的服务器都同意现在是什么时候:-)
发布于 2012-02-10 08:14:33
一种方法是获取服务器时间和本地时间之间的差异,并将其用于时间计算。
示例:
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);显然,在接收到服务器时间时,必须保存差异。
https://stackoverflow.com/questions/9224494
复制相似问题