A timer Demo that synchronizes multiple clients using trust.
The client sends time T1, the server sends time T2 after receiving the message, and the client records time T3 after receiving the message.
The network delay between the server and the client can be recorded as Delay=(T3 - T1) / 2
.The time difference between the server and the client (different devices have different time) can be recorded as diff_time = T2 + Delay - Now()
.The client can use diff_time
to calculate the current server time.
All state attributes of the timer are saved in the server. The client sends a message to modify the state of the timer in the server, and then broadcasts it to all clients.
When the client receives the status information sent by the server, it saves the information and starts to continuously calculate the accumulated time of the timer or the remaining time of the countdown.
mode
Timer mode. Timer
/CountDown
state
Running state. Start
/Stop
.
time
The start time of the timer or the end time of the countdown.
counter
The accumulated time of the timer or the remaining time of the countdown.
We can see from the figure that the values of the four timers or countdowns displayed in the screenshot are inconsistent. The error mainly comes from two aspects.
We used diff_ Time = T2 + Delay - Now()
to calculate the difference between local time and server time for conversion between local time and server time. T2 + Delay
represents the current time of the server. Delay represents the difference between the time when the server sends the response and the time when the response arrives at the client. The problem is that Delay cannot be calculated accurately. We can only use (T3 - T1) / 2
to estimate the value of Delay.
The client refreshes the display value of the timer at a fixed frequency. Different client tasks have different execution times, and the calculated values are different. This error is usually within a dozen milliseconds. You can reduce this error by increasing the refresh rate.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。