首页 > 解决方案 > 如何增加服务器发送事件的重新打开时间?

问题描述

我正在努力显示来自服务器发送事件的通知。我检查了每次浏览器在每次连接关闭后大约 3 秒尝试重新连接源时。该事件的调用速度太快,因此我的服务器也已加载。

那么如何更改重新开放时间以增加?我必须至少做 60 秒,所以告诉我该怎么做?

我正在尝试以下代码。

<table class="table" id="notification"></table>
<script type="text/javascript">
    var ssevent = null;
    if (!!window.EventSource) {
        ssevent = new EventSource('ssevent.php');

        ssevent.addEventListener('message', function(e){
            if(e.data){
                json = JSON.parse(e.data);
                if(json){
                    json.forEach(function(v,i){
                        html = "<tr><td>"+ v.text +"</td><td>"+ v.date +"</td></tr>";
                    });
                    $('#notification').append(html);
                }
            }
        }, false);

        ssevent.addEventListener('error', function(e) {
            if (e.readyState == EventSource.CLOSED){
                console.log("Connection was closed.");
            }
        }, false);
    } else {
        console.log('Server-Sent Events not support in your browser');
    }
</script>

事件流文件如下。

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();

$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();

if($result){
    $json = array();
    foreach ($result as $row){
        $json[] = array(
            'text' => $row['event_text'],
            'date' => date("Y-m-d H:i", $row['event_time']),
        );
    }

    echo "data: ". json_encode($json) . "\n\n";
    flush();
}

标签: phptimeoutserver-sent-events

解决方案


现在我有我的答案了。


控制重新连接超时:

在关闭每个服务器发送的事件连接后,浏览器会在大约 3 秒内尝试重新连接到源。在尝试重新连接之前,您可以通过以 开头的行retry:然后添加等待的毫秒数来更改该超时。

我更改了下面的代码并开始按我的意愿工作。

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

include_once "config.php";
$time = isset($_SESSION['last_event_time']) ? $_SESSION['last_event_time'] : time();

$result = $db->quesry("SELECT * FROM event_noti WHERE event_time < {$time} ")->rows;
$_SESSION['last_event_time'] = time();

echo "retry: 60000\n"; // 60 seconds, to wait for next connection.

$json = array();
if($result){
    foreach ($result as $row){
        $json[] = array(
            'text' => $row['event_text'],
            'date' => date("Y-m-d H:i", $row['event_time']),
        );
    }
}

echo "data: ". json_encode($json) . "\n\n";
flush();

来源


推荐阅读