Introduction to Server-Sent Events in HTML5

Source: Internet
Author: User

HTML5 has a Server-Sent Events (SSE) function that allows the Server to push data to the client. (Usually data push ). Let's take a look at the simple sequence diagram of traditional WEB Application Communication:

<! Doctype html>

 
   
    <meta charset="UTF-8">
    <title>Basic SSE Example</title>
   
  <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>

The backend first has a basic_sse.php page:

<?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);
  }
?>

You can use Apache Server so that we can place them on sinaappengine. when you access firefox1_basic_see.html, the current time will be returned:

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);

To improve the function, if we use Node. js to return HTML, the code is 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);

On the console, run node datepush2.js and access http: // 127.0.0.1: 1234/sse2 in the browser. The effect is as follows:

If (typeof (EventSource )! = "Undefined "){

   // Yes! Server-sent events support!
   }
 else{
   // Sorry! No server-sent events support in our system
   }
 

Current browser support:

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:


We hope this will be helpful for your WEB application development.

Articles you may be interested in:

HTML5 File Upload progress
Custom data-* features in Html 5

Drag and Drop In HTML5

W3C HTML5 SSE


Author: Petter Liu
Source: http://www.cnblogs.com/wintersun/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.
This article is also published in Petter Liu Blog, my independent Blog.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.