Computer >> Computer tutorials >  >> Programming >> HTML

How Server-Sent Events Works in HTML5?


Server-sent events standardize how we stream data from the server to the client. To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document.

The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events.

The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently. Following is a simple example of web application which would expect server time.

How Server-Sent Events Works in HTML5?

You can try to run the following code to learn how to use Server-Sent Events in HTML5

Example

<!DOCTYPE HTML>
<html>
   <head>
      <script type="text/javascript">
         document.getElementsByTagName("eventsource")[0].addEventListener("server-time", eventHandler, false);
         function eventHandler(event){
            // Alert time sent by the server
            document.querySelector('#ticker').innerHTML = event.data;
         }
      </script>
   </head>
   <body>
      <div id="sse">
         <eventsource src="/cgi-bin/ticker.cgi" />
      </div>
      <div id="ticker" name="ticker">
         [TIME]
      </div>
   </body>
</html>

Finally, following is the ticker.cgi written in perl −

#!/usr/bin/perl
print "Content-Type: text/event-stream\n\n";
while(true){
   print "Event: server-time\n";
   $time = localtime();
   print "Data: $time\n";
   sleep(5);
}