【发布时间】:2012-03-22 20:16:27
【问题描述】:
我最近发现了 EventSource,YUI3 有一个 Gallery 模块来规范化和回退行为,这就是我在示例中选择使用的,因为我已经使用了该框架。
所以我搜索了很多,阅读了许多博客、帖子和示例,所有这些都显示了几乎相同的东西:如何设置基本的 SSE 事件。我现在有 6 个打开/消息/错误/关闭事件触发的示例。
我没有的(我希望 this link 会给我的)是如何触发对我的应用程序更有用的 SSE 事件的示例,我正在尝试一个名为“更新”的事件.
这是我的基本测试页面:http://codefinger.co.nz/public/yui/eventsource/test.php(它也可能是一个 html 文件,这里还没有 php 代码)
这是 EventSource 构造函数中的“message.php”:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
/**
* Constructs the SSE data format and flushes that data to the client.
*
* @param string $id Timestamp/id of this connection.
* @param string $msg Line of text that should be transmitted.
*/
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
while(true) {
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
sleep(10);
}
// I was hoping calling this file with a param might allow me to fire an event,
// which it does dutifully, but no browsers register the 'data : update' - though
// I do see the response in Firebug.
if( $_REQUEST['cmd'] ){
sendMsg($serverTime, $_REQUEST['cmd'] );
}
?>
从上面的实时示例中,您可以看到我尝试使用 YUI 的 io 模块发送带有参数的请求,以在单击“更新”按钮时触发我的“更新”事件。正如您在 Firebug 的 Net 面板中看到的那样,它似乎有效,但我的事件没有得到处理(我意识到上面的脚本将再次运行该循环,我只想在连接的浏览器中处理我的事件,然后我将删除/清理)。
我在这部分做错了吗?还是我做错了什么更根本的事情?我正在尝试推送事件以响应我的 UI 状态变化。
This SO question 似乎接近了,@tomfumb 评论说他的下一个问题是“如何在建立初始连接后向客户端发送新事件 - 现在我看到 PHP 必须永远不会停止执行。”但可以肯定的是,我只会在事件发生时发送事件......而不是连续发送......
【问题讨论】:
标签: php javascript events server-push server-sent-events