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. 记一次裸迁 MySQL 经历

    记一次裸迁MySQL经历 前言:博主企业有一台企业阿里云机器,因为安装了云锁,造成服务器动不动就给我所死服务器.(就是那种 chattr +i /bin/bash ,分分钟日死狗 )趁着周末,Boos ...

  2. 锁&锁与指令原子操作的关系 & cas_Queue

    锁 锁以及信号量对大部分人来说都是非常熟悉的,特别是常用的mutex.锁有很多种,互斥锁,自旋锁,读写锁,顺序锁,等等,这里就只介绍常见到的, 互斥锁 这个是最常用的,win32:CreateMute ...

  3. MongoDB修改器的使用2

    1."$inc"的使用 主要用来增加数值,比如网站的访问量,点击量,流量等 db.games.insert({game:"pinball",user:" ...

  4. Web前端优化最佳实践及工具集锦

    Web前端优化最佳实践及工具集锦 发表于2013-09-23 19:47| 21315次阅读| 来源Googe & Yahoo| 118 条评论| 作者王果 编译 Web优化Google雅虎P ...

  5. c#事件与委托

    C#.net 目录(?)[-] 将方法作为方法的参数 将方法绑定到委托 事件的由来 事件和委托的编译代码 委托事件与Observer设计模式 范例说明 Observer设计模式简介 实现范例的Obse ...

  6. Unity3D 常用插件

    1.FX Maker FX Maker是一款制作特效的工具,它专为移动操作系统做了优化.FX Maker包括300种Prefab特效,300种纹理结构.100种网格.100种曲线效果.支持英文和韩文, ...

  7. AngularJS in Action读书笔记1——扫平一揽子专业术语

    前(fei)言(hua): 数月前,以一个盲人摸象的姿态看了一些关于AngularJS的视频书籍,留下了我个人的一点或许是指点迷津或许是误人子弟的读后感.自以为已经达到熟悉ng的程度,但是因为刚入公司 ...

  8. Responsive Web CSS – 在线响应式布局创建器

    如果您已经使用了 CSS 或前端框架,创建响应式布局应该不难. 然而,如果你刚涉足这类布局,Responsive Web CSS 可以帮助你快速上手. 这是一个基于 Web 的工具,使任何人都可以通过 ...

  9. [Basic] The most basic things about java

    [Basic] The most basic things about java // */ // ]]>   [Basic] The most basic things about java ...

  10. java设计模式(四)--单例模式

    Singleton最熟悉不过了,下面学习单例模式.转载:http://zz563143188.iteye.com/blog/1847029 单例对象(Singleton)是一种常用的设计模式.在Jav ...