服务器发送的事件在3-4秒后收到

时间:2016-09-20 16:03:00

标签: html5 server-sent-events

在阅读this page的服务器发送事件时,我对事件的发生时间感到困惑。基本上,example shown有一个PHP脚本将系统时间发送到网页:

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

    $time = date('r');
    echo "data: The server time is: {$time}\n\n";
    flush();
?>

当页面接收并呈现它时:

if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("demo_sse.php");
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}

我的困惑是服务器似乎每3-4秒发送一次消息:

The server time is: Tue, 20 Sep 2016 11:55:12 -0400
The server time is: Tue, 20 Sep 2016 11:55:16 -0400
The server time is: Tue, 20 Sep 2016 11:55:20 -0400
The server time is: Tue, 20 Sep 2016 11:55:23 -0400
The server time is: Tue, 20 Sep 2016 11:55:28 -0400
The server time is: Tue, 20 Sep 2016 11:55:32 -0400
The server time is: Tue, 20 Sep 2016 11:55:35 -0400
The server time is: Tue, 20 Sep 2016 11:55:39 -0400
The server time is: Tue, 20 Sep 2016 11:55:43 -0400
The server time is: Tue, 20 Sep 2016 11:55:46 -0400
The server time is: Tue, 20 Sep 2016 11:55:50 -0400
The server time is: Tue, 20 Sep 2016 11:55:53 -0400
The server time is: Tue, 20 Sep 2016 11:55:57 -0400
The server time is: Tue, 20 Sep 2016 11:56:01 -0400
The server time is: Tue, 20 Sep 2016 11:56:04 -0400
The server time is: Tue, 20 Sep 2016 11:56:08 -0400
The server time is: Tue, 20 Sep 2016 11:56:12 -0400
The server time is: Tue, 20 Sep 2016 11:56:15 -0400

但是,我没有在服务器端或客户端看到这种延迟。它是网站服务器和浏览器之间的网络延迟吗?还是别的什么?

1 个答案:

答案 0 :(得分:3)

默认重试为3秒,如http://www.html5rocks.com/en/tutorials/eventsource/basics/所示 查看该链接上的“控制重新连接超时部分”。 您可以通过发送行重试来自定义它:100 强制执行仅100ms的重试时间间隔。