The HTML5 server sends an event that allows a web page to get updates from the server. It was possible to do this in the past, as long as the page had to ask if any updates were available. Updates can arrive automatically by sending events through the server. Examples: Facebook/Twitter updates, stock price updates, new blog posts, race results, etc. All major browsers support sending events from the server, except for Internet Explorer. Instance resolution: Create a new Every time an update is received, it occurs When For the following example, we wrote an additional piece of code to detect browser support for events sent by the server: In order for the above example to work, you also need servers (such as PHP and ASP) that can send data updates. The syntax of the server-side event flow is very simple. Set the Content-Type header to text/event-stream. Now you can start sending the event stream. ASP Code (VB) (demo_sse.asp): Code interpretation: Set the header “Content-Type” to “text/event-stream” Stipulate that pages are not cached Output date sent (always starts with “data:”) Refresh output data to a web page In the above example, we use the Event Description Onopen When the connection to the server is opened Onmessage When a message is received Onerror When something goes wrong 11.48.1. Server-Sent event-one-way messaging ¶
Server-Sent
an event means that a web page automatically gets updates from the server. 11.48.2. Browser support ¶
11.48.3. Receive Server-Sent event notifications ¶
EventSource
object is used to receive event notifications sent by the server:Example ¶
varsource=newEventSource("demo_sse.php");source.onmessage=function(event){document.getElementById("result").innerHTML+=event.data+"<br>";};
EventSource
object, and then specify the URL of the page that sent the update (“demo_sse.php” in this case)
onmessage
event
onmessage
the event occurs, push the received data into the element whose id is “result” 11.48.4. Detect Server-Sent event support ¶
if(typeof(EventSource)!=="undefined")
{
// Browser supports Server Server
// Some code.....
}
else
{
// Browser does not support Server Server..
}
11.48.5. Server-side code example ¶
Example ¶
<?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();
?>
<%
Response.ContentType="text/event-stream"
Response.Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>
11.48.6. EventSource object ¶
onmessage
event to get the message. However, other events can be used: