HTML5 SSE


HTML5 Server-Sent Events


HTML5 server-sent event allows web pages to obtain updates from the server.


Server-Sent event - one-way messaging

The Server-Sent event refers to the web page automatically getting updates from the server.

It was also possible to do this before, if the webpage had to ask if an update was available. By sending events through the server, updates can arrive automatically.

Examples: Facebook/Twitter updates, valuation updates, new blog posts, event results, etc.


Browser Support

Internet Explorer

Server-sent events are supported by all major browsers except Internet Explorer.


Receive Server-Sent event notification

EventSource object is used to receive server-sent event notification:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<h1>获取服务端更新数据</h1>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
{
	var source=new EventSource("demo_sse.php");
	source.onmessage=function(event)
	{
		document.getElementById("result").innerHTML+=event.data + "<br>";
	};
}
else
{
	document.getElementById("result").innerHTML="抱歉,你的浏览器不支持 server-sent 事件...";
}
</script>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

Instance analysis:

  • Creation A new EventSource object, and then specify the URL of the page to send the update (in this case "demo_sse.php")

  • The onmessage event will occur each time an update is received

  • When the onmessage event occurs, push the received data into the element with the id "result"


Detect Server-Sent Event support

In the following example, we wrote an additional piece of code to detect browser support for server-sent events:

if(typeof(EventSource)!=="undefined" )
{
// Browser supports Server-Sent
// Some code...
}
else
{
/ / The browser does not support Server-Sent..
}


Server-Side Code Example

In order for the above example to work, you will also need a server that can send data updates (such as PHP and ASP).

The syntax of server-side event streaming is very simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending the event stream.

Example

##<?phpheader
('Content-Type: text/ event-stream');
header('Cache-Control: no-cache' );

$time = date('r');echo "
data: The server time is: {$time} \n\n";
flush();
?>
ASP Code (VB) (demo_sse.asp):

<%
Response.ContentType="text/event-stream"
Response. Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>
Code explanation:

  • Set the header "Content-Type" to "text/event-stream"

  • Specify that the page is not cached

  • Output sending date (always starts with "data: ")

  • Refresh output data to the web page


EventSource object

In the above example, we use the onmessage event to get the message. However, other events can also be used:

EventDescriptiononopenWhen A connection to the server is openedonmessageWhen a message is receivedonerrorWhen An error occurred