服务器与客户端时钟同步
在我的应用程序中,我有一个服务器和 x 个客户端。当Client启动时,他从Server获取当前的系统时间。每个客户端都必须使用服务器时间,不能使用自己的系统时间。
现在我的问题:在客户端上运行时钟的最佳方法是什么?该时钟从当前服务器时间开始,并几乎与其同步运行,而不需要每 x 秒接收一次服务器时间?
目标是在客户端上显示运行时钟以及服务器时间。
客户端时钟可能具有的容差约为 24 小时内 1 秒。
在我的解决方案中,我得到了一个每 500 毫秒触发一次的计时器,并在计时器执行时对服务器时间进行 500 毫秒计数。但这不是一个好的解决方案:)因为客户端时钟与服务器时间不同。
感谢您的回复
In my application I have a Server and x Clients. When a Client starts, he obtained the current System time from the Server. Every Client has to work with the Server time and can´t use his own System time.
Now my Question: What is the best way to run a clock on the Client that starts with the current Server time and run nearly synchronous to it without to receive the Server time every x seconds?
The goal is to display a runing clock with the Server time on the client.
The tolerance that the client clock may have is about 1second in 24hours.
In my solution I got a Timer that trigger every 500ms and count 500ms on the Server time when the Timer executes. But this is not a good solution :) because the Client clock differ from the Server time.
Thanks for your reply
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您几乎肯定应该使用已建立的时钟同步方法,例如网络时间协议,而不是构建自己的时钟同步方法定制解决方案。它将为您提供比您自己获得的更好的结果,并且您还有一个额外的好处,即所有服务器都同意现在的时间:-)
You should almost certainly use an established clock synchronization method such as the Network Time Protocol rather than building your own custom solution. It will provide you with better results than you will make yourself, and you have the added benefit that all your servers agree about what time it is :-)
我找到了一个完全适合我的情况的解决方案。
我没有使用
System.currentTimeMillis()
,而是使用System.nanoTime()
。System.nanoTime()
独立于系统时钟。当我收到当前服务器时间时,我会从系统中保存额外的 ns。然后根据服务器时间接收到的ns时间与当前nanoTime加上服务器时间之差计算出当前服务器时间。
示例:
谢谢
I find a Solution that fits perfectly for my situation.
Instead of using
System.currentTimeMillis()
, I'm usingSystem.nanoTime()
.System.nanoTime()
is independent from the System clock.When I receive the current Server time, I save additional the ns from the System. Then the current Server time will be calculated with the difference between the ns time from Server time receiving and the current nanoTime plus the Server time.
Example:
Thx
执行此操作的一种方法是获取服务器时间和本地时间之间的差异,并将其用于时间计算
示例:
显然必须在服务器启动时保存差异时间已收到。
One way to do this is to get the difference between the server time and the local time and use that for time calculations
Example:
Obviously the difference must be saved the moment the server time is received.