PhoneGap中文网

 找回密码
 立即注册
查看: 17567|回复: 0

html5之sse服务器发送事件EventSource介绍

[复制链接]

87

主题

87

帖子

327

积分

中级会员

Rank: 3Rank: 3

积分
327
发表于 2017-8-29 20:58:55 | 显示全部楼层 |阅读模式
本帖最后由 w8484855@qq.com 于 2017-8-29 21:00 编辑

本文和大家分享的主要是html5的sse服务器发送事件EventSource相关内容,一起来看看吧,希望对大家学习html5有所帮助。
  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 + "
";
  };
  服务器端代码实例
  <?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 + "
";
  };
  source.onerror=function()
  {
  console.log("EventSource failed.");
  };
  }else
  {
  document.getElementById("result").innerHTML="抱歉,你的浏览器不支持 server-sent 事件...";
  }
  我们会发现,控制台打印如下:
QQ截图20170409201802.png
不停的进入链接、和错误,详情请点击
  那是因为php代码只是简单的echo,并没有连续输出,我们把上面php代码做如下改进
  <?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,有如下解决方案:
  引入
  eventsource.min.js
  就可以完美解决。

来源:Haorooms

it营
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

ionic4视频教程

Archiver|手机版|小黑屋| PhoneGap中文网 ( 京ICP备13027796号-1 )  

GMT+8, 2024-3-29 13:09 , Processed in 0.048633 second(s), 31 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表