body{
font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif;
}

      HTML5有一个Server-Sent Events(SSE)功能,允许服务端推送数据到客户端。(通常叫数据推送)。我们来看下,传统的WEB应用程序通信时的简单时序图:

现在Web App中,大都有Ajax,是这样子:

基于数据推送是这样的,当数据源有新数据,它马上发送到客户端,不需要等待客户端请求。这些新数据可能是最新闻,最新股票行情,来自朋友的聊天信息,天气预报等。

      数据拉与推的功能是一样的,用户拿到新数据。但数据推送有一些优势。 你可能听说过Comet, Ajax推送, 反向Ajax, HTTP流,WebSockets与SSE是不同的技术。可能最大的优势是低延迟。SSE用于web应用程序刷新数据,不需要用户做任何动作。
      你可能听说过HTML5的WebSockets,也能推送数据到客户端。WebSockets是实现服务端更加复杂的技术,但它是真的全双工socket, 服务端能推送数据到客户端,客户端也能推送数据回服务端。SSE工作于存在HTTP/HTTPS协议,支持代理服务器与认证技术。SSE是文本协议你能轻易的调试它。如果你需要发送大部二进制数据从服务端到客户端,WebSocket是更好的选择。

      让我们来看一下很简单示例,先是前端basic_sse.html:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Basic SSE Example</title>
  </head>
  <body>
    <pre id="x">Initializing...</pre>
    <script>
    var es = new EventSource("basic_sse.php");
    es.addEventListener("message", function(e){
      document.getElementById("x").innerHTML += "\n" + e.data;
      },false);
    </script>
  </body>
</html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

后端先是一个basic_sse.php页面:

<?php
header("Content-Type: text/event-stream");
while(true){
  echo "data:".date("Y-m-d H:i:s")."\n\n";
  @ob_flush();@flush();
  sleep(1);
  }
?>

您可以使用Apache Server 这里我们把它们放在SinaAppEngine上,浏览器FireFox访问basic_see.html时,将继续返回当前时间:

代码中数据格式是data: datetime.  在这儿,我们还可以使用Node.js来做服务端,datepush.js代码是这样的:

var http = require("http");
http.createServer(function(request, response){
  response.writeHead(200, { "Content-Type": "text/event-stream" });
  setInterval(function(){
    var content = "data:" +
      new Date().toISOString() + "\n\n";
    response.write(content);
    }, 1000);
  }).listen(1234);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

完善一下功能,如果我们用Node.js来返回HTML,代码是这样的datepush.js:

var http = require("http"), fs = require("fs");
var port = parseInt( process.argv[2] || 1234 );
http.createServer(function(request, response){
  console.log("Client connected:" + request.url);
  if(request.url!="/sse"){
    fs.readFile("basic_sse.html", function(err,file){
      response.writeHead(200, { 'Content-Type': 'text/html' });
      var s = file.toString();  //file is a buffer
      s = s.replace("basic_sse.php","sse");
      response.end(s);
      });
    return;
    }
  //Below is to handle SSE request. It never returns.
  response.writeHead(200, { "Content-Type": "text/event-stream" });
  var timer = setInterval(function(){
    var content = "data:" + new Date().toISOString() + "\n\n";
    var b = response.write(content);
    if(!b)console.log("Data got queued in memory (content=" + content + ")");
    else console.log("Flushed! (content=" + content + ")");
    },1000);
  request.connection.on("close", function(){
    response.end();
    clearInterval(timer);
    console.log("Client closed connection. Aborting.");
    });
  }).listen(port);
console.log("Server running at http://localhost:" + port);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }在控制台,运行 node datepush2.js,在浏览器中访问 http://127.0.0.1:1234/sse2 ,效果如下截图:

 

假设您曾经有javascript编程经验,代码并不难看懂。前端是HTML5,后端可以是PHP, JSP, Node.js, Asp.net等应用。

Tips: 不所有浏览器都支持SSE,可以使用以下Javascript来判断:

if(typeof(EventSource)!=="undefined"){
   // Yes! Server-sent events support!
   }
 else{
   // Sorry! No server-sent events support in our system
   }
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

目前浏览器支持情况:

Browser

Supported

Notes

Internet Explorer

No

IE is not supported

Mozilla Firefox

Yes

Version 6.0

Google Chrome

Yes

GC is Supported

Opera

Yes

Version 11

Safari

Yes

Version 5.0

希望对您WEB应用程序开发有帮助。

您可能感兴趣的文章:

HTML5上传文件显示进度

Html 5中自定义data-*特性

HTML5中实现拖放效果

W3C HTML5 SSE

作者:Petter Liu

出处:http://www.cnblogs.com/wintersun/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

该文章也同时发布在我的独立博客中-Petter Liu Blog

HTML5的Server-Sent Events介绍的更多相关文章

  1. HTML5的Server-Sent Events介绍////////////////zzz

    HTML5有一个Server-Sent Events(SSE)功能,允许服务端推送数据到客户端.(通常叫数据推送).我们来看下,传统的WEB应用程序通信时的简单时序图: 现在Web App中,大都有A ...

  2. html5/css3响应式布局介绍及设计流程

    html5/css3响应式布局介绍 html5/css3响应式布局介绍及设计流程,利用css3的media query媒体查询功能.移动终端一般都是对css3支持比较好的高级浏览器不需要考虑响应式布局 ...

  3. Play Framework, Server Sent Events and Internet Explorer

    http://www.tuicool.com/articles/7jmE7r Next week I will be presenting at Scala Days . In my talk I w ...

  4. 翻译1-在SQL Server 2016中介绍微软R服务

    在SQL Server 2016中介绍微软R服务 源自:http://www.sqlservercentral.com/articles/Microsoft/145393/ 作者:tomakatrun ...

  5. server sent events

    server sent events server push https://html5doctor.com/server-sent-events/ https://developer.mozilla ...

  6. HTML5 服务器发送事件(Server-Sent Events)介绍

    w3cschool菜鸟教程 Server-Sent 事件 - 单向消息传递 Server-Sent 事件指的是网页自动获取来自服务器的更新. 以前也可能做到这一点,前提是网页不得不询问是否有可用的更新 ...

  7. HTML5分析实战WebSockets基本介绍

    HTML5 WebSockets规范定义了API,同意web使用页面WebSockets与远程主机协议的双向交流. 介绍WebSocket接口,并限定了全双工通信信道,通过套接字网络.HTML5 We ...

  8. SQL Server Extended Events 进阶 2:使用UI创建基本的事件会话

    第一阶中我们描述了如何在Profiler中自定义一个Trace,并且让它运行在服务器端来创建一个Trace文件.然后我们通过Jonathan Kehayias的 sp_SQLskills_Conver ...

  9. SQL Server Extended Events 进阶 1:从SQL Trace 到Extended Events

    http://www.sqlservercentral.com/articles/Stairway+Series/134869/ SQL server 2008 中引入了Extended Events ...

随机推荐

  1. C# 进制转换 (没有数值的长度限制)

    曾经在大学时做过一个c的进制转换算法,那时由于技术的局限性,数值的大小受到限制(系统数据类型长度限制),多年以后,自己那台学习机陈旧后感觉要报废了,整理了一下里面的东西,偶尔在一个角落里发现了这个转换 ...

  2. android TextView 文字垂直的设置

    <TextView android:id="@+id/tv_status" android:layout_width="wrap_content" and ...

  3. VS报错:The build tools for v140 (Platform Toolset = 'v140') cannot be found

    VS低版本打开高版本常会出现的错: The build tools for v140 (Platform Toolset = 'v140') cannot be found. To build usi ...

  4. 【博客美化】06.添加QQ交谈链接

    博客园美化相关文章目录: [博客美化]01.推荐和反对炫酷样式 [博客美化]02.公告栏显示个性化时间 [博客美化]03.分享按钮 [博客美化]04.自定义地址栏logo [博客美化]05.添加Git ...

  5. 【博客美化】04.自定义地址栏logo

    博客园美化相关文章目录: [博客美化]01.推荐和反对炫酷样式 [博客美化]02.公告栏显示个性化时间 [博客美化]03.分享按钮 [博客美化]04.自定义地址栏logo [博客美化]05.添加Git ...

  6. javascript中的错误处理机制

    × 目录 [1]对象 [2]类型 [3]事件[4]throw[5]try[6]常见错误 前面的话 错误处理对于web应用程序开发至关重要,不能提前预测到可能发生的错误,不能提前采取恢复策略,可能导致较 ...

  7. HTML5移动Web开发(九)——优化浏览器视口宽度设置

    每个移动设备都有自己默认的视口宽度,如果你不显示的设置它的值,在渲染页面的时候你可能会得不到你想要的效果.比如,如果不设置iPhone的视口宽度,它将会按照980像素的宽度渲染页面,如果你的页面设计不 ...

  8. Windows Azure Service Bus (5) 主题(Topic) 使用VS2013开发Service Bus Topic

    <Windows Azure Platform 系列文章目录> 项目文件,请在这里下载 在笔者之前的文章中Windows Azure Service Bus (1) 基础 介绍了Servi ...

  9. JS&CSS文件请求合并及压缩处理研究(四)

    本篇将会尝试对之前的代码进行相关的单元测试,验证路径合并规则的覆盖率及正确性. 熟悉 ASP.NET MVC 开发的朋友应该知道,微软在MVC框架下集成了一款名为 Microsoft.VisualSt ...

  10. 基于HTML5的WebGL电信网管3D机房监控应用

    先上段视频,不是在玩游戏哦,是规规矩矩的电信网管企业应用,嗯,全键盘的漫游3D机房: http://www.hightopo.com/guide/guide/core/3d/examples/exam ...