HTML SSE


Events are created by traditional web applications and sent to the webserver. A simple click on a connection, for example, requests a new page from the server.

Client-sent events are the types of events that flow from the web browser to the webserver.

Along with HTML5, WHATWG Web Applications 1.0 implements Server-Sent Events, which flow from the webserver to the web browsers (SSE). SSE allows you to send DOM events from your webserver to the visitor's browser in real-time.

The event streaming approach creates a long-term link with the server, transmitting data to the client as soon as new data becomes available, obviating the need for continuous polling.


SSE Web Application


You'll need to add an aspect to the document to use Server-Sent Events in a web application.

The element's src attribute should point to a URL that establishes a persistent HTTP link and sends a data stream containing events.

The URL would point to a PHP, PERL, or Python script that would submit event data in a consistent manner. The following is a basic web application that would need server time.



<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
/* event handling logic goes here */
</script>
</head>
<body>

<div id = "sse">
<eventsource src = "/cgi-bin/ticker.cgi" />
</div>

<div id = "ticker">
<TIME>
</div>

</body>
</html>



Server Side Script for SSE


A server-side script can submit the Content-type header with the text/event-stream type, as shown below.



print "Content-Type: text/event-stream\n\n";



The server-side script will submit an Event: tag followed by the event name after setting the Content-Type. The example below will submit Server-Time as the event name, followed by a newline character.



print "Event: server-time\n";



The final step is to submit event data using the Data: tag, which is followed by an integer of string value and then a newline character, as shown below:



$time = localtime();
print "Data: $time\n";



Finally, here is the full ticker.cgi script 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);
}