How to work with long-lasting http requests

[亡魂溺海] 提交于 2019-12-13 00:27:49

问题


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


回答1:


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.




回答2:


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.




回答3:


The best solution would be to use AJAX requests. Once an ajax request times out you can send it again by using JavaScript(you can show some button). This is probably the best practice to handle timeouts.



来源:https://stackoverflow.com/questions/16542202/how-to-work-with-long-lasting-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!