在java中长轮询 [英] Long polling in java

查看:164
本文介绍了在java中长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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编写的。发送请求后,如果服务器已响应,如何继续检查客户端。我应该在什么时间间隔将请求发送到服务器。我完全糊涂了。我是Web技术的初学者。我尝试使用Google搜索,但所有示例都基于客户端是java脚本或JSP。任何人都可以给出一个正确的教程链接,客户端是一个java HTTp应用程序或提供一个例子(即实现长轮询)。

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).

推荐答案

对HTTPURLConnection的getInputStream的调用会返回阻塞流。在此流上调用读取将阻止该线程,直到服务器提供数据,您无需继续轮询数据。

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.

在一个单独的线程中调用read,并在不关闭连接的情况下将HTTPURLConnection保留在范围内。这可以让你在可用时恢复数据。从服务器收到200OK后,在同一连接上发回另一个请求以保持打开状态。
(这是因为你没有实现请求超时。)

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.)

这篇关于在java中长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆