Server-Sent Events (SSE) enable a web page to receive automatic updates from a server without needing to constantly request updates.
This technology is used for real-time updates such as Facebook or Twitter feeds, stock prices, news updates, sports scores, and more.
The numbers in the table indicate the earliest browser version that fully supports Server-Sent Events (SSE).
The EventSource object is employed to receive notifications from server-sent events.
var source = new EventSource(“demo_sse.php”); source.onmessage = function(event) { document.getElementById(“result”).innerHTML += event.data + “<br>”; }; |
Here’s an explanation of the example:
In the “tryit” example above, additional lines of code were included to verify browser support for server-sent events.
if(typeof(EventSource) !== “undefined”) { // Yes! Server-sent events support! // Some code….. } else { // Sorry! No server-sent events support.. } |
To enable the example above to function, you require a server capable of sending data updates, such as PHP or ASP.
Here’s a simple syntax for server-side event streaming. Set the “Content-Type” header to “text/event-stream” to begin sending event streams.
Example PHP code (demo_sse.php):
<?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(); ?> |
Code in ASP (VB) (demo_sse.asp):
<% Response.ContentType = “text/event-stream” Response.Expires = -1 Response.Write(“data: The server time is: ” & now()) Response.Flush() %> |
Here’s an explanation of the code:
In the examples above, we utilized the onmessage
event to receive messages. However, other events are also available:
Events |
Description |
onopen |
When a connection is established with the server |
onmessage |
Upon receiving a message |
onerror |
In the event of an error |