全部的
HTML5 Rocks提供了一个关于服务器发送事件(SSE)的入门教程:
http://www.html5rocks.com/en/tutorials/eventsource/basics/
但是,我不理解一个重要的概念——是什么触发了服务器上导致消息发送的事件?
换句话说,在HTML5示例中,服务器仅发送时间戳once:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
如果我正在构建一个实际的示例-例如,Facebook风格的"墙"或股票报价器,其中服务器会在每次某个数据发生更改时向客户端"推送"一条新消息,那么这是如何工作的呢?
换句话说...Does the PHP script have a loop that runs continuously, checking for a change in the data, then sending a message every time it finds one? If so - how do you know when to end that process?个
或者-PHP脚本是否只是发送消息,然后结束(就像HTML5Rock示例中的情况一样)?如果是这样的话-您如何获得持续的更新?浏览器只是定期轮询PHP页面吗?如果是,那怎么会是"服务器发送的事件"呢?这与用JavaScript编写setInterval函数(使用Ajax定期调用PHP页面)有何不同?
抱歉,这可能是一个非常天真的问题.但我所能找到的例子中没有一个能清楚地说明这一点.
[更新]
我认为我的问题措辞不好,所以这里有一些澄清.
假设我有一个网页,可以显示苹果股票的最新价格.
当用户第一次打开页面时,页面会使用我的"流"的URL创建一个事件源.
var source = new EventSource('stream.php');
我的问题是,"stream.php"应该如何工作?
这样地?(伪代码):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
function sendMsg($msg) {
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
flush();
}
while (some condition) {
// check whether Apple's stock price has changed
// e.g., by querying a database, or calling a web service
// if it HAS changed, sendMsg with new price to client
// otherwise, do nothing (until next loop)
sleep (n) // wait n seconds until checking again
}
?>
换句话说,"stream.php"是否在客户端"连接"到它时保持打开状态?
如果是这样的话-这是否意味着您运行stream.php
个线程的数量与您拥有的并发用户数量一样多?如果是这样的话-这是远程可行的,还是构建应用程序的合适方式?你怎么知道什么时候你可以END个stream.php
的实例呢?
我天真的感觉是,如果是这样的话,PHPisn't是一种适合这种服务器的技术.但到目前为止,我看到的所有演示都表明PHP可以胜任这项工作,这就是为什么我如此困惑的原因...