5

我已经编写了用于长轮询的服务器端代码。我想用java编写客户端程序。因此,根据长轮询,客户端发送一个由服务器提供帮助的请求,服务器在事件发生时响应该请求,然后客户端发送一个新请求。

所以我面临的麻烦是用java编写的客户端。在我发送请求后,如果服务器已响应它,如何继续检查客户端。我应该以什么时间间隔将请求发送到服务器。我完全糊涂了。我是 Web 技术的初学者。我尝试在谷歌上搜索,但所有示例都基于客户端是 java 脚本或 JSP。任何人都可以提供一个链接到一个适当的教程,客户端是一个java HTTp应用程序或提供一个例子(即实现长轮询)。

4

1 回答 1

7

The call to HTTPURLConnection's getInputStream gives back a blocking stream. Calling a read on this stream will block the thread till data is available from the server, you need not keep polling for data.

Call the read in a separate thread and keep the HTTPURLConnection in scope without closing the connection. This should get you back the data nwhen available. Once you receive a 200OK from the server, send back another request on the same connection to keep it open. (This is if you have not implemented a request timeout.)

于 2013-07-23T06:39:43.240 回答