这次给大家带来怎样用h5的sse服务器发送eventsource事件,用h5的sse服务器发送eventsource事件的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
我前面文章讲过数据大屏,里面的数据时时更新。还有时时更新的股票数据,Facebook/Twitter 更新、估价更新、新的博文、赛事结果等等,都需要数据时时更新。之前我们一般都是请求服务器,看看有没有可以更新的数据。html5提供了Server-Sent Events方法,通过服务器发送事件,更新能够自动到达。
Server-Sent Events使用
Server-Sent Events使用很简单,通过EventSource 对象来接受服务器端消息。有如下事件:
onopen 当通往服务器的连接被打开
onmessage 当接收到消息
onerror 当发生错误
检测 Server-Sent 事件支持
if(typeof(EventSource)!=="undefined")
{
// 浏览器支持 Server-Sent
// 一些代码.....
}
else
{
// 浏览器不支持 Server-Sent..
}
接收 Server-Sent 事件通知
var source=new EventSource("haorooms_sse.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
服务器端代码实例
<?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();
?>链接事件和报错事件都加上
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中文网其它相关文章!
相关阅读:
以上就是怎样用h5的sse服务器发送EventSource事件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号