简体   繁体   中英

Long polling in 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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