Why doesn't this PHP code (comet) work?

≯℡__Kan透↙ 提交于 2019-12-13 06:22:26

问题


set_time_limit(0);

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
flush();

while($i < 10)
{
    sleep(1);
    $i++;
    echo $i;
    flush();
}

Why doesn't my code print out 1, then wait and print 2 then wait and print 3. Instead, it just waits 10 seconds and prints out 12345678910 all at once?

Is there a way to print it in chunks as I want?


回答1:


It's likely because of output buffering. Try adding this at the top of the file to close all the open buffers:

while(ob_get_level() > 0) {
    ob_end_flush();
}

You can also add ob_flush() after the flush() command in your code:

$i++;
echo $i;
flush();
ob_flush();

(Note that you should only have to do one of them, not both, but try it)...




回答2:


The problem could be you need some junk data to start the streaming in some webbrowsers.

A quote from this link

Firstly, the server must push some junk data (around 2k) to the browser before you push the real data. So just write out some javascript comments to the browsers first.

for (int i = 0; i < 10; i++) {   
  write.print("<!——————————————–this is junk—————–!>"); 
}


来源:https://stackoverflow.com/questions/4519789/why-doesnt-this-php-code-comet-work

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