简体   繁体   中英

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?

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:

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

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—————–!>"); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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