PHP 和事件 - 在脚本终止之前不会刷新到客户端
PHP and events - flush to client does not happen until the script dies
我正在尝试创建一个将事件发送到网页的简单页面,但我无法让 PHP 在页面终止之前发送输出。
我正在使用 PHP-FPM 和 php5.6.27.
这是我的简单 HTML 页面:
<html>
<head>
<title>test events</title>
</head>
<body>
testing events
<ul id="pingEventList" style="float: left"></ul>
<ul id="messageEventList" style="float: left"></ul>
<script>
var evtSource=new EventSource("./s_events.php?auth=e3b164ef33d802c45da829b8f1240d16");
var pingEventList=document.getElementById('pingEventList');
var messageEventList=document.getElementById('messageEventList');
evtSource.onmessage=function (e){
var newElement=document.createElement("li");
newElement.innerHTML="message: "+e.data;
messageEventList.appendChild(newElement);
};
evtSource.addEventListener("initial", function (e){
var newElement=document.createElement("li");
// var obj=JSON.parse(e.data);
newElement.innerHTML="initial info "+e.data;
console.log("initial info "+e.data);
pingEventList.appendChild(newElement);
}, false);
evtSource.addEventListener("modified", function (e){
var newElement=document.createElement("li");
// var obj=JSON.parse(e.data);
newElement.innerHTML="modified info "+e.data;
console.log("modified info "+e.data);
pingEventList.appendChild(newElement);
}, false);
evtSource.onerror=function (e){
console.log("EventSource failed.", e);
// while(pingEventList.firstChild){
// pingEventList.removeChild(pingEventList.firstChild);
// }
// alert("EventSource failed.");
};
// evtSource.close();
</script>
</body>
</html>
这是我的 PHP 页面:
<?php
@set_time_limit(0); // Disable time limit
// Prevent buffering
if(function_exists('apache_setenv')){
@apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
while(ob_get_level() !=0){
ob_end_flush();
}
ob_implicit_flush(1);
ignore_user_abort(false);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
header('X-Accel-Buffering: off'); // Disables FastCGI Buffering on Nginx
$sleep_time = 1; //0.5 // seconds to sleep after the data has been sent
$exec_limit_time = 15; //600; // the time limit of the script in seconds
$keep_alive_time = 30; //300; // The interval of sending a signal to keep the connection alive
$client_reconnect = 1; // the time client to reconnect after connection has lost in seconds
$keep_alive_start = time();
$exec_limit_start = time();
$ts_last_used = intval(isset($_SERVER["HTTP_LAST_EVENT_ID"])?$_SERVER["HTTP_LAST_EVENT_ID"]:0);
echo 'retry:'.($client_reconnect*1000)."\n";
$event = [
'id' => $ts_last_used++,
'event' => 'initial',
'data' => "[\ndata:".'INITIAL DATA'."\ndata:]",
];
_send_event_data($event);
while(1){
// Did the connection fail?
if(connection_status() !=CONNECTION_NORMAL){
break;
}else{
$event = [
'id' => $ts_last_used++,
'event' => 'modified',
'data' => '{"id":"stuff here too"}',
];
_send_event_data($event);
}
// Sleep for x seconds
usleep($sleep_time*1000000);
if($exec_limit_start+$exec_limit_time<time()){
break;
}
if($keep_alive_start+$keep_alive_time<time()){
$keep_alive_start = time();
echo ': '.sha1(mt_rand())."\n\n";
}
}
// If this is reached, then the 'break'
// was triggered from inside the while loop
//
// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
function _send_event_data($info){
global $keep_alive_start;
if(isset($info['id'])){
echo 'id:'.$info['id']."\n";
}
if(isset($info['event'])){
echo 'event:'.$info['event']."\n";
}
echo 'data:'.$info['data']."\n";
if(!isset($info['more_to_come'])||!$info['more_to_come']){
echo "\n";
}
$keep_alive_start = time();
@ob_end_flush();
flush();
}
我尝试了各种可能的解决方案,但我无法弄清楚。我也将 PHP-FPM 更改为 mod_php(我正在使用 apache)以防它是 PHP_FPM,但我没有任何成功。
我乐于接受建议
我明白了...是 apache 保存了输出,这是我的 fast-cgi usign php-fpm:
的新配置
<IfModule fastcgi_module>
#php-fpm
AddHandler php5-fcgi .php .html
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/local/www/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/local/www/cgi-bin/php5-fcgi -flush -socket /var/run/php-fpm.sock -pass-header Authorization -idle-timeout 600
<Directory /usr/local/www/cgi-bin>
Require all granted
</Directory>
</IfModule>
不同之处在于 -flush
添加到 FastCgiExternalServer
,现在输出不再缓冲并立即输出(感谢此页面,我能够找到答案:http://www.jeffgeerling.com/blog/2016/streaming-php-disabling-output-buffering-php-apache-nginx-and-varnish )
我正在尝试创建一个将事件发送到网页的简单页面,但我无法让 PHP 在页面终止之前发送输出。
我正在使用 PHP-FPM 和 php5.6.27.
这是我的简单 HTML 页面:
<html>
<head>
<title>test events</title>
</head>
<body>
testing events
<ul id="pingEventList" style="float: left"></ul>
<ul id="messageEventList" style="float: left"></ul>
<script>
var evtSource=new EventSource("./s_events.php?auth=e3b164ef33d802c45da829b8f1240d16");
var pingEventList=document.getElementById('pingEventList');
var messageEventList=document.getElementById('messageEventList');
evtSource.onmessage=function (e){
var newElement=document.createElement("li");
newElement.innerHTML="message: "+e.data;
messageEventList.appendChild(newElement);
};
evtSource.addEventListener("initial", function (e){
var newElement=document.createElement("li");
// var obj=JSON.parse(e.data);
newElement.innerHTML="initial info "+e.data;
console.log("initial info "+e.data);
pingEventList.appendChild(newElement);
}, false);
evtSource.addEventListener("modified", function (e){
var newElement=document.createElement("li");
// var obj=JSON.parse(e.data);
newElement.innerHTML="modified info "+e.data;
console.log("modified info "+e.data);
pingEventList.appendChild(newElement);
}, false);
evtSource.onerror=function (e){
console.log("EventSource failed.", e);
// while(pingEventList.firstChild){
// pingEventList.removeChild(pingEventList.firstChild);
// }
// alert("EventSource failed.");
};
// evtSource.close();
</script>
</body>
</html>
这是我的 PHP 页面:
<?php
@set_time_limit(0); // Disable time limit
// Prevent buffering
if(function_exists('apache_setenv')){
@apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
while(ob_get_level() !=0){
ob_end_flush();
}
ob_implicit_flush(1);
ignore_user_abort(false);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
header('X-Accel-Buffering: off'); // Disables FastCGI Buffering on Nginx
$sleep_time = 1; //0.5 // seconds to sleep after the data has been sent
$exec_limit_time = 15; //600; // the time limit of the script in seconds
$keep_alive_time = 30; //300; // The interval of sending a signal to keep the connection alive
$client_reconnect = 1; // the time client to reconnect after connection has lost in seconds
$keep_alive_start = time();
$exec_limit_start = time();
$ts_last_used = intval(isset($_SERVER["HTTP_LAST_EVENT_ID"])?$_SERVER["HTTP_LAST_EVENT_ID"]:0);
echo 'retry:'.($client_reconnect*1000)."\n";
$event = [
'id' => $ts_last_used++,
'event' => 'initial',
'data' => "[\ndata:".'INITIAL DATA'."\ndata:]",
];
_send_event_data($event);
while(1){
// Did the connection fail?
if(connection_status() !=CONNECTION_NORMAL){
break;
}else{
$event = [
'id' => $ts_last_used++,
'event' => 'modified',
'data' => '{"id":"stuff here too"}',
];
_send_event_data($event);
}
// Sleep for x seconds
usleep($sleep_time*1000000);
if($exec_limit_start+$exec_limit_time<time()){
break;
}
if($keep_alive_start+$keep_alive_time<time()){
$keep_alive_start = time();
echo ': '.sha1(mt_rand())."\n\n";
}
}
// If this is reached, then the 'break'
// was triggered from inside the while loop
//
// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
function _send_event_data($info){
global $keep_alive_start;
if(isset($info['id'])){
echo 'id:'.$info['id']."\n";
}
if(isset($info['event'])){
echo 'event:'.$info['event']."\n";
}
echo 'data:'.$info['data']."\n";
if(!isset($info['more_to_come'])||!$info['more_to_come']){
echo "\n";
}
$keep_alive_start = time();
@ob_end_flush();
flush();
}
我尝试了各种可能的解决方案,但我无法弄清楚。我也将 PHP-FPM 更改为 mod_php(我正在使用 apache)以防它是 PHP_FPM,但我没有任何成功。
我乐于接受建议
我明白了...是 apache 保存了输出,这是我的 fast-cgi usign php-fpm:
的新配置<IfModule fastcgi_module>
#php-fpm
AddHandler php5-fcgi .php .html
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/local/www/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/local/www/cgi-bin/php5-fcgi -flush -socket /var/run/php-fpm.sock -pass-header Authorization -idle-timeout 600
<Directory /usr/local/www/cgi-bin>
Require all granted
</Directory>
</IfModule>
不同之处在于 -flush
添加到 FastCgiExternalServer
,现在输出不再缓冲并立即输出(感谢此页面,我能够找到答案:http://www.jeffgeerling.com/blog/2016/streaming-php-disabling-output-buffering-php-apache-nginx-and-varnish )