我不知道如果这是一个问题,但是,我做一个饲料从php到javascript使用服务器发送事件而不是ajax。所有的工作都很好,除了,睡眠在服务器端,保持事件源阻塞网页流。我做了一个非常简单的代码来测试,我得到了相同的结果。
我将把代码放在上面。
服务器发送的事件挂起页面流?它不像ajax做异步请求?
主要问题是:服务器发送的事件挂起代码流,我的意思是,页面等待EventSource保持代码执行,每次EventSource打开连接或接收消息。当我在服务器端代码上放置睡眠时,我可以清楚地看到这一点,我的页面停止睡眠时间,运行3秒,然后再次挂起。当我做一个ajax调用,调用是异步的,所以代码保持运行与ajax在后台,即使我把一个睡眠在服务器端。我希望你现在能明白=p
test.php
@set_time_limit(0);
//send the proper header
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if(function_exists('apache_setenv')){
@apache_setenv('no-gzip',1);
}
@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
for($i = 0; $i < ob_get_level(); $i++){
ob_end_flush();
}
ob_implicit_flush(1);
$startedAt = time();
do {
$time = time();
echo "id: $startedAt " . PHP_EOL;
echo "data: {n";
echo "data: "msg": "$time", n";
echo "data: "id": $startedAtn";
echo "data: }n";
echo PHP_EOL;
//@ob_flush();
@ob_end_flush();
@flush();
usleep(0.5*1000000);
} while(true);
HTML if(!!window.EventSource) {
var source = new EventSource('test.php');
source.addEventListener('open', function(event) {
console.log('open');
}, false);
source.addEventListener('message', function(event) {
var data = JSON.parse(event.data);
console.log(event.data);
},false);
}
正如Daniel自己回答的那样,问题可能出在会话锁上。
session_write_close();
也解决了我的问题