HTML5 Server-Sent Events
HTML5 Server-Sent Events
HTML5 server-sent event allows web pages to obtain updates from the server.
Browser support
All major browsers support server-sent events, except Internet Explorer.
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.
Get the data sent by the server on the client side and update
<!DOCTYPE html> <html> <body> <h1>获得服务器更新</h1> <div id="result"> </div> <script>if(typeof(EventSource)!=="undefined"){ var source=new EventSource("http://www.w3school.com.cn/example/html5/demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br />"; }; }else{ document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";} </script> </body> </html>
The supporting server code (PHP or ASP) is as follows:
<?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 explanation:
Set the header "Content-Type" to "text/event-stream"
Specify that the page is not cached
Output the sending date (always starting with "data: ")
Refresh output data to the web page
Detect Server-Sent event support
In the following example, we wrote an additional code to detect the event sent by the server Browser support:
if(typeof(EventSource)!=="undefined") { // 浏览器支持 Server-Sent // 一些代码..... } else { // 浏览器不支持 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
<?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 代码 (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 will not be 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 messages. However, other events can also be used:
Events Events Receive message
onerror When an error occurs