java java中的长轮询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17802276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Long polling in java
提问by Ashwin Surana
I have written my server side code for long polling. I want to write the client program in 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.
我已经为长轮询编写了服务器端代码。我想用java编写客户端程序。因此,根据长轮询,客户端发送一个请求,该请求得到服务器的帮助,服务器在发生事件时响应该请求,然后客户端发送一个新请求。
So the trouble I am facing is with the client side which is to be written in 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. I tried googling about this but all the examples are based on client side being a java script or 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编写的客户端。发送请求后,如果服务器已响应,如何继续检查客户端。我应该以什么时间间隔继续向服务器发送请求。我完全糊涂了。我是 Web 技术的初学者。我试过谷歌搜索这个,但所有的例子都是基于客户端是一个 java 脚本或 JSP。任何人都可以提供指向正确教程的链接,其中客户端是 Java HTTp 应用程序或提供一个示例(即实现长轮询)。
回答by Raji
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.
对 HTTPURLConnection 的 getInputStream 的调用返回一个阻塞流。对此流调用读取将阻塞线程,直到数据从服务器可用,您无需继续轮询数据。
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.)
在单独的线程中调用读取并将 HTTPURLConnection 保持在范围内而不关闭连接。这应该可以让您在可用时取回数据。从服务器收到 200OK 后,在同一连接上发回另一个请求以使其保持打开状态。(这是在您尚未实现请求超时的情况下。)