HTML5有一個Server-Sent Events(SSE)功能,容許服務端推送數據到客戶端。(一般叫數據推送)。咱們來看下,傳統的WEB應用程序通訊時的簡單時序圖:javascript
如今Web App中,大都有Ajax,是這樣子:php
基於數據推送是這樣的,當數據源有新數據,它立刻發送到客戶端,不須要等待客戶端請求。這些新數據多是最新聞,最新股票行情,來自朋友的聊天信息,天氣預報等。html
數據拉與推的功能是同樣的,用戶拿到新數據。但數據推送有一些優點。 你可能據說過Comet, Ajax推送, 反向Ajax, HTTP流,WebSockets與SSE是不一樣的技術。可能最大的優點是低延遲。SSE用於web應用程序刷新數據,不須要用戶作任何動做。
你可能據說過HTML5的WebSockets,也能推送數據到客戶端。WebSockets是實現服務端更加複雜的技術,但它是真的全雙工socket, 服務端能推送數據到客戶端,客戶端也能推送數據回服務端。SSE工做於存在HTTP/HTTPS協議,支持代理服務器與認證技術。SSE是文本協議你能輕易的調試它。若是你須要發送大部二進制數據從服務端到客戶端,WebSocket是更好的選擇。前端
讓咱們來看一下很簡單示例,先是前端basic_sse.html:java
<!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>
後端先是一個basic_sse.php頁面:node
<?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代碼是這樣的:web
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);
完善一下功能,若是咱們用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);
在控制檯,運行 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
}
目前瀏覽器支持狀況:
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 |