简体   繁体   English

为什么此PHP代码(comet)不起作用?

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

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? 为什么我的代码没有打印出1,然后等待并打印2,然后等待并打印3。相反,它只等待10秒并立即打印出12345678910?

Is there a way to print it in chunks as I want? 有没有一种方法可以按需要将其打印成块?

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: 您还可以在代码中的flush()命令之后添加ob_flush()

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

(Note that you should only have to do one of them, not both, but try it)... (请注意,您只需要执行其中之一,而不是两者都可以,但是请尝试一下)...

The problem could be you need some junk data to start the streaming in some webbrowsers. 问题可能是您需要一些垃圾数据才能在某些Web浏览器中开始流式传输。

A quote from this link 链接的报价

Firstly, the server must push some junk data (around 2k) to the browser before you push the real data. 首先,在推送真实数据之前,服务器必须将一些垃圾数据(大约2k)推送到浏览器。 So just write out some javascript comments to the browsers first. 因此,只需先向浏览器写一些JavaScript注释即可。

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

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

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