How do you determine exactly when, accounting for

2019-07-18 17:01发布

I am building an application where it is important to know exactly when a user submitted a request to the server. This is different from the time at which the server received the request, because there is an interval of time -- that is often subject to the vagaries of network traffic and cell reception -- between the moment the user presses submit and the server receives the POST request.

The interaction is through a web browser with JavaScript, so any solution that involves JavaScript is acceptable. I thought about getting current time on the user's computer or smartphone using JavaScript and using that as a timestamp on the submitted request, but that by itself wouldn't be reliable because the clock on the user's computer could be off. Please assume that the clock on the server is accurate.

2条回答
Lonely孤独者°
2楼-- · 2019-07-18 17:24

You could try this:

http://jehiah.cz/a/ntp-for-javascript

to calculate an accurate JavaScript clock, then pass that value with your POST request.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-18 17:46

I don't think it's possible to get an exact value. I think the best you can do is send a very small calibration AJAX request that equivalents the client time with the server time. That's what I've done anyhow.

Edit for elaboration

Basically make an AJAX call to a server endpoint with the client timestamp (clock). As soon as the server receives the client timestamp retrieve and store the server timestamp along with it. At this point you can assume the times are relatively equivalent. You won't know the network overhead, so they will be different; also their clock could be in a different time zone or just "off".

After you have this equivalence you can use the difference of the two times to calibrate any other times from the client:

  • clientTime0 - serverTime0 = clientServerDelta
  • (clientTimeX - clentServerDelta) will be about the same in server time as when clientTimeX was recorded.
查看更多
登录 后发表回答