HTML5 - Server Sent Events


Advertisements

Server Sent Events

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>

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

You can get demo of Server Sent Events here

Advertisements