php无限循环和彗星


php infinite loop and comet?

我的php脚本似乎有问题,但我不知道它是什么。唯一可能的问题是与缓存有关,但我不能确定。这是我的脚本,我会告诉你代码下面发生了什么:

<?php
set_time_limit(0);
header('Content-Type:text/event-stream');
$prevmod=$lastmod=filemtime('chattext.txt');
function waitformod(){
global $lastmod;
global $prevmod;
while($prevmod==$lastmod){
    usleep(100000);
    clearstatcache();
    $lastmod=filemtime('chattext.txt');
    }
echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
flush();
$prevmod=$lastmod;
}
while(true){
waitformod();
}
?>

这应该与JavaScriptEventSource一起使用,并在修改时发送chatterxt.txt的内容。但是,该文件不输出任何内容。我认为这是因为无限循环。有什么办法解决这个问题吗?

这样的东西效果更好吗?

<?php
set_time_limit(0);
header('Content-Type:text/event-stream');
$prevmod = $lastmod = filemtime('chattext.txt');
function waitformod(){
    global $lastmod;
    global $prevmod;
    while($prevmod == $lastmod) {
        usleep(100000);
        clearstatcache();
        $lastmod = filemtime('chattext.txt');
    }
    echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
    flush();
    $prevmod = $lastmod;
}
while(1) {
    waitformod();
}

当前代码看起来像是读取文件、输出文件、等待更改,然后终止。