我已经在我的网络应用程序中使用 服务器发送事件 和 事件源 进行了实现。基本上,我的JavaScript代码如下:
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);
}
}
根据在PHP Event Source keeps executing找到的答案,"text/event-stream"头应该会自动关闭连接,但在我的情况下没有关闭。
我在window.onbeforeunload事件中添加了eventsource.close,但它没有关闭事件。
window.onbeforeunload = function() {
myEventSource.close();
myEventSource = null;
};
如果我查看浏览器的网络部分,我可以看到头文件是(在添加最大循环30后): Content-Type: text/event-stream;charset=UTF-8
响应头:
Access-Control-Allow-Origin: * Cache-Control: no-cache Connection: Keep-Alive Content-Type: text/event-stream;charset=UTF-8 Server: Apache/2.4.18 (Ubuntu) Date: Thu, 26 Apr 2018 20:29:46 GMT Expires: Thu, 19 Nov 1981 08:52:00 GMT
请求头:
Connection: keep-alive Accept: text/event-stream Cache-Control: no-cache 注意:我确认脚本仍在运行,通过日志和检查Apache2进程与bash(ps -ax | grep -c apache2)始终增加。
if (connection_aborted()) { exit();` 我使用这个已经有一段时间了,可以很好地杀死进程。例如:https://dev59.com/9Knka4cB1Zd3GeqPPH8X#49081040
- Lawrence Cherone