HTML5 Server-Sent Events
HTML5 server-sent event allows web pages to obtain updates from the server.
Server-Sent Event - One-Way Messaging
Browser support
# #All major browsers support server-sent events, except Internet Explorer.
Receive Server-Sent event notificationThe EventSource object is used to receive event notifications sent by the server:
<!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>
demo_sse.php code
<?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(); ?>
Create a new EventSource object and then specify to send updates The URL of the page ("demo_sse.php" in this example)
Every time an update is received, the onmessage event will occur
When the onmessage event occurs, push the received data Enter the element with the id "result"
Detect Server-Sent event supportIn the following example, we wrote an additional paragraph Code to detect browser support for events sent by the server:
if(typeof(EventSource)!=="undefined"){ // Browser support 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 to be able to send data updates Servers (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
<?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(); ?>
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"
Specifies that the page is not cached
Output the sending date (always starts with "data: ")
Refresh output data to the web page
##EventSource object
Event | Description |
When the connection to the server is opened | |
When a message is received | |
When an error occurs |