简体   繁体   English

Web服务器是否可以使用长时间的输出流来响应HTTP请求?

[英]Is it possible for a web server to respond to a HTTP request with an extended time stream of output?

When you run PHP scripts in the console, all the standard output text from that script shows up in the console window while the script is running. 在控制台中运行PHP脚本时,脚本运行时,该脚本的所有标准输出文本都会显示在控制台窗口中。 Is it possible for a browser window to similarly receive status reports in the browser while a lengthy PHP script is running, instead of getting all the output dumped at the conclusion of the script? 在运行冗长的PHP脚本时,浏览器窗口是否有可能在浏览器中类似地接收状态报告,而不是在脚本结束时转储所有输出?

Yes. 是。 Just call flush() and ob_flush() periodically. 只需定期调用flush()和ob_flush()即可。 It's important to write some output at least every 120 seconds to keep the connection to the browser alive. 重要的是至少每120秒编写一些输出,以保持与浏览器的连接有效。

A rough example: 一个粗略的例子:

    while(!$done) {
        //doWork();
        echo number_format(100 * ($workDone/$workTotal)) . "% ";
        flush();
        ob_flush();
    }

Edit: here's an arbitrary proof of concept that works in my env: 编辑:这是在我的环境中有效的概念的任意证明:

print('hello');
print(str_repeat(".\n", 2048));
flush();
//this might be a safe way to only flush the buffer if necessary?
if(ob_get_length())
    ob_flush();
sleep(60);

Yes, one thing you'll need to worry about if you have a particularly long execution time is timing out. 是的,如果执行时间特别长,您需要担心的一件事就是超时。 This can occur as a PHP timeout or as a browser timeout (generally about 2 minutes). 这可能是由于PHP超时或浏览器超时(通常约2分钟)而发生。

This PHP documentation about connection handling has quite a bit of good information about keeping connections alive. 这个有关连接处理的 PHP文档中有很多有关保持连接活动的良好信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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