2016年10月6日 星期四

Server Sent Events on html5

Ref : https://www.tutorialspoint.com/html5/server_sent_events.htm


It takes the updates from server and gives result on web browsers.Before take updates from server,browser would have to ask, if any updates were available in web servers.

Example

HTML5 code should be as follows
<html>
   <body>
   
      <h1> Server updates</h1>
      <div id="result"></div>
   
      <script>
         if(typeof(EventSource) !== "undefined") {
            var source = new EventSource("demo_sse.php");
         
            source.onmessage = function(event) {
               document.getElementById("result").innerHTML += event.data + "<br>";
            };
         }
      
         else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support ";
         }
      </script>
   </body>
</html>

會去一直執行  

     var source = new EventSource("demo_sse.php");
         
            source.onmessage = function(event) {
               document.getElementById("result").innerHTML += event.data + "<br>";
            };

event.data 為  demo_sse.php 所echo 出來的文字....

demo_sse.php

Server Code should be in PHP,It looks like as follows
<?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();
?>



沒有留言:

張貼留言