English 中文(简体)
HTML5 - Server Sent Events
  • 时间:2024-09-17

HTML5 - Server Sent Events


Previous Page Next Page  

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>
      <span id="result"></span>
   
      <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 pke as follows

<?php
   header( Content-Type: text/event-stream );
   header( Cache-Control: no-cache );
   
   $time = date( r );
   echo "data: The server time is: {$time}

";
   flush();
?>