Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with long-lasting http requests

I have a long-lasting http request (a lot of computation in the back-end).

Currently it's all synchronous, while the server computer, the browser doesn't see the output/result. After a while, the connection is dropped and an timeout error is displayed in the browser.

I'd like to return some info to the browser right away, and make it wait for the result. How to achieve this?

Please note, that the Java back-end is synchronous. So a solution would require some hack in the servlet/front end possibly requiring javascript requests.. ?

like image 488
Roay Spol Avatar asked Jan 28 '26 16:01

Roay Spol


2 Answers

You probably want to use the COMET pattern. It's like the AJAX pattern, only featuring long-held HTTP requests to simulate a feed. See here for a detailed explanation.

Basically, you fire off a request, the server holds it, then replies when it has something of interest. At the point of receiving the reply, you immediately fire off another long-held request.

This time-sequence makes it feel like a feed.

In your case, it could just return "yeah, I'm working on it" immediately and then reply with "still processing 10% done dude" and so on until you get back "done".

Things like node.js are really good at implementing this kind of functionality.

Although, as you're using a synchronous Java back end, you may need some kind of indication somewhere that progress is being made. Possibly a database.

like image 143
Jeff Watkins Avatar answered Jan 30 '26 05:01

Jeff Watkins


Timeout won't occure as long as you write something to output stream (it can even be spaces, don't forget to call flush()).

Such long-lasting request makes sence when you, for example, print a large report, which is shown to the user subsequently as it is generated.

In all other cases, return the waiting page to the user and use periodical AJAX requests to ask if the processing has finished. When nothing changes and the browser is showing loading, it is not a good user experience.

like image 20
Danubian Sailor Avatar answered Jan 30 '26 04:01

Danubian Sailor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!