HTML5的Server-Sent Events功能的使用

客户端代码示例

1 //创建一个新的 EventSource 对象,然后规定发送更新的页面的 URL。
2 var source = new EventSource("http://localhost:8080/test/20150129/test.php");
3 //每接收到一次更新,就会发生onmessage事件,在控制台输出
4 source.onmessage=function(event){
5     console.log(event.data);
6 };

服务器代码示例

1 <?php
2     //把 "Content-Type" 报头设置为 "text/event-stream",这样就可以发送事件流了    
3     header('Content-Type: text/event-stream');
4     $rand = rand(1,100);
5     echo "data:this is a test{$rand}\n\n";
6     //把缓冲区的数据全部输出
7     flush();

 

注意事项:

  服务器端的输出数据要以"data:"字符串开头,以\n\n结尾

 

参考网址:

  http://segmentfault.com/q/1010000002315641

  http://www.w3school.com.cn/html5/html_5_serversentevents.asp

  https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events

posted on 2015-01-29 17:16  sustudy  阅读(371)  评论(0编辑  收藏  举报

导航