我发现HTML5 Server Sent Events可能就是我所需要的。所以我尝试了一个简单的测试页面,通过SSE检索更新。
demo.html
<!DOCTYPE html>
<html>
<body>
<h1>SSE Output</h1>
<div id="result"></div>
<h1>Debug Console</h1>
<div id="status"></div>
<script>
//SSE si compatible
if(typeof(EventSource)!=="undefined")
{
var i = 1;
var source=new EventSource("demo_sse.php?ver=2");
//Lorsque le serveur envoie un message
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + " #" + i + "<br />";
i++;
}
//EventListener
source.addEventListener('message', function(e)
{
console.log(e.data);
//document.getElementById("status").innerHTML+= "Message Recevied<br />";
}, false);
source.addEventListener('open', function(e)
{
// Connection was opened.
document.getElementById("status").innerHTML+= "Connection #" + i + " opened<br />";
}, false);
source.addEventListener('error', function(e)
{
if (e.readyState == EventSource.CLOSED)
{
// Connection was closed.
document.getElementById("status").innerHTML+= "Connection closed<br />";
}
}, false);
//Validation de l'origine du serveur
if (event.origin != 'https://mydomain.com')
{
alert('Looks like the Origin of the EventSource (the schedule\'s live update service) wasn\'t coming from our secure server!');
//return;
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
demo_see.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$ver = 2;
$time = date("H:i:s");
if ($ver != $_GET["ver"])
{
echo "data: Page updated at: {$time}\n\n";
flush();
}
?>
问题是,如果版本匹配或不匹配,每个像3秒钟就会打开连接,所以我认为客户端询问服务器而不是服务器询问客户端。我想要的是在客户端和服务器之间保持开放连接,以便服务器可以在计划中进行任何更新时发送更改。
任何提示都将不胜感激!
由于
答案 0 :(得分:1)
浏览器每3秒重新连接一次,因为您的服务器代码不能保持连接打开。它发送时间然后结束。尝试更像这样的东西:
while (true) {
echo "data: Page updated at: {$time}\n\n";
flush();
sleep(1);
}