Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.

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
"; while(true){ print "Event: server-time
"; $time = localtime(); print "Data: $time
"; sleep(5); }
Advertisements