HTML 5 服务器发送事件

接收 Server-Sent 事件通知
EventSource 对象用于接收服务器发送事件通知:
实例
var source=new EventSource("demo_sse.php");
source.onmessage=function(event)
  {
  document.getElementById("result").innerHTML+=event.data + "<br />";
  };
检测 Server-Sent 事件支持
在上面的 TIY 实例中,我们编写了一段额外的代码来检测服务器发送事件的浏览器支持情况:
if(typeof(EventSource)!=="undefined")
  {
  // Yes! Server-sent events support!
  // Some code.....
  }
else
  {
  // Sorry! No server-sent events support..
  }
PHP 代码 (demo_sse.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();
?>

EventSource 对象

在上面的例子中,我们使用 onmessage 事件来获取消息。不过还可以使用其他事件:

事件描述
onopen 当通往服务器的连接被打开
onmessage 当接收到消息
onerror 当错误发生
posted @ 2014-07-14 21:05  韵脚学员  阅读(342)  评论(0编辑  收藏  举报