简体   繁体   English

Java中的长轮询

[英]Long polling in java

I have written my server side code for long polling. 我已经为长时间轮询编写了服务器端代码。 I want to write the client program in java. 我想用Java编写客户端程序。 So as per long polling, the client sends a request which is help by the server and the server responds to the request when an event occurs and then client sends a new request. 因此,按照长时间轮询,客户端发送一个由服务器帮助的请求,并且服务器在事件发生时响应该请求,然后客户端发送一个新请求。

So the trouble I am facing is with the client side which is to be written in java. 所以我要面对的麻烦是用Java编写的客户端。 After I send the request, how to keep checking in the client side if the server has responded to it or not. 发送请求后,如何继续在客户端检查服务器是否响应。 At what intervals should I keep sending the request to the server. 我应该以什么间隔将请求发送到服务器。 I am totally confused. 我很困惑。 I am quite a beginner to Web technologies. 我是Web技术的初学者。 I tried googling about this but all the examples are based on client side being a java script or JSP. 我尝试使用谷歌搜索,但是所有示例均基于客户端,即Java脚本或JSP。 Could anyone give a link to a proper tutorial with client side being a java HTTp application or provide an example on this (ie to achieve long polling). 任何人都可以通过客户端为Java HTTp应用程序提供指向适当教程的链接,或在此上提供示例(即实现长时间轮询)。

The call to HTTPURLConnection's getInputStream gives back a blocking stream. 对HTTPURLConnection的getInputStream的调用将返回阻塞流。 Calling a read on this stream will block the thread till data is available from the server, you need not keep polling for data. 在此流上调用read将阻塞线程,直到服务器上有可用数据为止,而无需继续轮询数据。

Call the read in a separate thread and keep the HTTPURLConnection in scope without closing the connection. 在一个单独的线程中调用read并将HTTPURLConnection保留在范围内,而无需关闭连接。 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. 从服务器收到200OK后,请在同一连接上发送回另一个请求以使其保持打开状态。 (This is if you have not implemented a request timeout.) (这是如果您尚未实现请求超时。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM