PHP服务器发送事件连接赢得';我关不上?
我已经在我的web应用程序上实现了一个。 在javascript中,我的代码基本上如下所示:PHP服务器发送事件连接赢得';我关不上?,php,server-sent-events,php-7.1,event-stream,Php,Server Sent Events,Php 7.1,Event Stream,我已经在我的web应用程序上实现了一个。 在javascript中,我的代码基本上如下所示: var myEventSource; if (typeof(EventSource) !== "undefined" && !myJsIssetFunction(viridem.serverSideEvent.config.reindexProcessingEvent)) { myEventSource = new EventSource('/my/url
var myEventSource;
if (typeof(EventSource) !== "undefined" && !myJsIssetFunction(viridem.serverSideEvent.config.reindexProcessingEvent)) {
myEventSource = new EventSource('/my/url/path.php?event=myevent');
EventSource.onmessage = function(e) {
[...] //Dealing with e.data that i received ...
}
}
在PHP方面,我有如下内容:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
//this or set_the_limit don't work but whatever I can deal without it
ini_set('max_execution_time', 300);
//ignore_user_abort(true); tried with true and false
bool $mustQuit = false;
while (!$mustQuit && connection_status() == CONNECTION_NORMAL) {
if(connection_aborted()){
exit();
}
[...] //doing some checkup
if ($hasChange) {
//Output stuffs
echo 'data:';
echo json_encode($result);
echo "\n\n";
ob_flush();
flush();
sleep(5);
}
}
如果我查看浏览器的网络部分,我可以看到标题是(在添加最大循环30后):
内容类型:文本/事件流;字符集=UTF-8
响应标题:
访问控制允许来源:*
缓存控制:没有缓存
连接:保持活力
内容类型:文本/事件流;字符集=UTF-8
服务器:Apache/2.4.18(Ubuntu)
日期:2018年4月26日星期四20:29:46 GMT
到期时间:1981年11月19日星期四格林威治标准时间08:52:00
请求标头:
连接:保持活力
接受:文本/事件流
缓存控制:没有缓存
注意:我确认脚本仍在使用日志运行,并通过使用始终递增的bash(ps-ax | grep-c apache2)检查apache2进程来确认脚本是否仍在运行。感谢@lawrencerone帮助,我确实发现您需要“输出数据”才能使连接中止工作 就我而言,我只是在需要的时候才输出数据 加入
if ($hasChange) {
//Output stuffs
echo 'data:';
echo json_encode($result);
echo "\n\n";
ob_flush();
flush();
sleep(5);
} else {
echo 'data:';
echo "\n\n";
ob_flush();
flush();
if(connection_aborted()){
exit();
}
sleep(5);
}
连接被中止开始工作。只需执行
while(true){if(连接被中止()){exit();
我已经使用了一段时间,并且可以很好地终止进程。例如:连接被中止()总是返回int(0):/不确定测试结果如何,但还需要忽略用户被中止(true);你已经关闭了。你不应该使用max_execution_time这个想法是,它确实会连续运行,并且只有在客户端断开连接时才会退出。你可以在循环中放入一个检查,以防止过度运行,但在大多数情况下并不需要。因为连接被中止了。你只需要确保你是一个lso定期发送保持活动状态消息。通常不超过每40秒一次。这将确保连接\u aborted()最多延迟40秒。
if ($hasChange) {
//Output stuffs
echo 'data:';
echo json_encode($result);
echo "\n\n";
ob_flush();
flush();
sleep(5);
} else {
echo 'data:';
echo "\n\n";
ob_flush();
flush();
if(connection_aborted()){
exit();
}
sleep(5);
}