本文摘自PHP中文网,作者php中世界最好的语言,侵删。
这次给大家带来怎样用h5的sse服务器发送EventSource事件,用h5的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")
{
// 浏览器支持 Server-Sent
// 一些代码.....
}
else
{
// 浏览器不支持 Server-Sent..
}
|
接收 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 8 | <? 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中文网其它相关文章!
相关阅读:
HTML的table鼠标拖拽排序该如何实现
怎样解决各种ie6-ie10的兼容问题
html怎样格式化json数据
以上就是怎样用h5的sse服务器发送EventSource事件的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html5存储页面或应用程序的私有自定义数据的data-* 属性
html5边玩边学(一)-画布详解
html5中的强制下载属性download使用
5个有用的css函数(分享)
html5实现调用摄像头并拍照功能
使用html5里的classlist操作css类的详细介绍
css实现等高布局的三种方式(代码示例)
几个解决兼容ie6\7\8不支持html5标签的几个方法
关于html5中标签video播放的新解析
html和html5的区别是什么
更多相关阅读请进入《EventSource》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 怎样用h5的sse服务器发送EventSource事件