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

   

获得服务器更新

The supporting server code (PHP or ASP) is as follows:

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

 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

Continuing Learning
||
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!