本文摘自PHP中文网,作者php中世界最好的语言,侵删。
这次给大家带来H5的之sse服务器发送事件EventSource详解,sse服务器发送事件EventSource的注意事项有哪些,下面就是实战案例,一起来看一下。前言
我前面文章讲过数据大屏,里面的数据时时更新。还有时时更新的股票数据,Facebook/Twitter 更新、估价更新、新的博文、赛事结果等等,都需要数据时时更新。之前我们一般都是请求服务器,看看有没有可以更新的数据。html5提供了Server-Sent Events方法,通过服务器发送事件,更新能够自动到达。
Server-Sent Events使用
Server-Sent Events使用很简单,通过EventSource 对象来接受服务器端消息。有如下事件:
onopen 当通往服务器的连接被打开
onmessage 当接收到消息
onerror 当发生错误
检测 Server-Sent 事件支持
1 2 3 4 5 6 7 8 9 | if (typeof(EventSource)!== "undefined" )
{
}
else
{
}
|
接收 Server-Sent 事件通知
1 2 3 4 5 | var source= new EventSource( "haorooms_sse.php" );
source.onmessage= function (event)
{
document.getElementById( "result" ).innerHTML+=event.data + "<br>" ;
};
|
服务器端代码实例
1 2 3 4 5 6 7 | <?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 ();
?>
|
链接事件和报错事件都加上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | if (typeof(EventSource)!== "undefined" )
{
var source= new EventSource( "server.php" );
source.onopen= function ()
{
console.log( "Connection to server opened." );
};
source.onmessage= function (event)
{
document.getElementById( "result" ).innerHTML+=event.data + "<br>" ;
};
source.onerror= function ()
{
console.log( "EventSource failed." );
};
}
else
{
document.getElementById( "result" ).innerHTML= "抱歉,你的浏览器不支持 server-sent 事件..." ;
}
|
我们会发现,控制台打印如下:

不停的进入链接、和错误,详情请点击
那是因为php代码只是简单的echo,并没有连续输出,我们把上面php代码做如下改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php
header( 'Content-Type: text/event-stream' );
header( 'Cache-Control: no-cache' );
$time = date ( 'r' );
$i = 0;
$c = $i + 100;
while (++ $i < $c ) {
echo "id: " . $i . "\n" ;
echo "data: " . $time . ";\n\n" ;
ob_flush();
flush ();
sleep(1);
}
?>
|
就不会出现不停错误了!
IE浏览器兼容解决方案
我们知道,IE浏览器并不支持EventSource,有如下解决方案:
引入
就可以完美解决。可以查看其github地址:https://github.com/Yaffle/EventSource 结合nodejs使用也很方便,直接
1 | npm install event-source-polyfill
|
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
H5实现可缩放的时钟动画
前缀data-属性和dataset的使用方法
以上就是H5的之sse服务器发送事件EventSource详解的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html5怎么嵌入视频
如何通过html5实现摇一摇的功能
介绍几款引人注目的html5/jquery动画插件详情
html5实践-使用css装饰图片画廊的代码分享(二)
一个完整的html对象是什么样的,如何生成?
html5关于web sql数据库的详细介绍
使用html5拍照示例代码介绍
5个好用的h5速查手册
html5中在元素或者选取的文本被拖动时触发的事件ondrag
如何使用html5 canvas绘制线条
更多相关阅读请进入《EventSource》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » H5的之sse服务器发送事件EventSource详解