如何轮询每 1 秒更新一次的服务器?
我有一个位于 http://foobar 的服务器,它返回一个 JSON 对象,其中包含有关过去一秒发生的事情的信息,例如,某事比如
{
time: 2011-06-08 05:07:33,
total: 235324,
average: 1233
}
轮询该服务器以便我获得每个更新的最佳方式是什么?我猜我不想只是轮询服务器,休眠 1 秒,然后再次轮询(因为轮询可能需要一些时间并导致事情延迟,所以我可能会错过一些更新)。我是否应该做一些事情,比如只睡眠 0.5 秒,轮询服务器,然后检查我收到的 JSON 对象是否与我上次收到的 JSON 具有不同的时间戳?
(顺便说一句,我是用 Java 做的,尽管我认为语言并不重要。)
I have a server at http://foobar that returns a JSON object containing information about things that happened in the past second, e.g., something like
{
time: 2011-06-08 05:07:33,
total: 235324,
average: 1233
}
What's the best way to poll this server so that I get every update? I'm guessing I don't want to just poll the server, sleep for 1 second, and then poll again (since the polling might take some time and cause things to get delayed, so I might miss some updates). Should I do something instead like sleep for only 0.5 seconds, poll the server, and then check whether the JSON object I receive has a different timestamp from the last JSON I received?
(I'm doing this in Java, by the way, though I don't think the language really matters.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要获取每个更新,服务器应该将更新推送给您,而不是向另一个方向推送。
例如,您应该考虑在客户端和服务器之间设置流,以便服务器可以向客户端发送事件通知。
If you need to get every update, the server should be pushing the updates to you instead of going the other direction.
For example, you should look into setting up a stream between the client and server so that the server can send event notifications to the client.
您可以使用“阻塞拉取”模式(不知道它的真实名称是什么):
此模式的优点是
缺点是客户端几乎总是处于阻塞状态。这可能不适合所有客户端应用程序
You can use the "blocking pull" pattern (don't know what it real name is):
The advantage of this pattern is
The disadvantage is that the client is almost always in a blocked state. This may not suit all client applications