Server Push events (server-sent events) is an integral part of the HTML 5 specification that can be used to push data from the service side in real time to the browser side. Compared to the similar COMET and WebSocket technologies, Server push events are easier to use and have less server-side changes. Server push events are the best choice for some types of applications.
WebSocket
Before introducing the HTML 5 Server push event, let's start by introducing some of the server-side data push technologies mentioned above. The first kind is WebSocket. WebSocket specification is an important part of HTML 5, has been supported by many mainstream browsers, there are many applications based on WebSocket development. As the name indicates, WebSocket uses a socket connection, based on the TCP protocol. After using WebSocket, a socket connection is actually established between the server side and the browser, which enables two-way data transfer. The WebSocket features are powerful, flexible to use and can be used in different scenarios. However, WebSocket technology is also more complex, including server-side and browser-side implementations are different from the general Web applications.
Polling
In addition to WebSocket, the other implementation is based on the HTTP protocol to achieve real-time push effect. The first is a simple poll, where the browser is timed to make a request to the server to query for data updates. This approach is relatively simple and can be solved to some extent. However, the time interval for polling needs to be carefully considered. The polling interval is too long, which causes the user to not receive the updated data in time, and the polling interval is too short, resulting in too many query requests and increasing the burden on the server side.
Disadvantages:
1: Polling is initiated by the client , then on the server can not determine whether I want to push the content has expired, because I can not tell whether a message has been pushed to all the client, the server needs to cache a large amount of data. If the data is kept in the database, then every request needs to query the database, which is a big challenge for database and system design.
2: The frequency of the request is too high , each time the request package contains the same data, which may not be anything to the PC, but for mobile clients, this should not be the best solution. Especially when it comes to the judgment of authority, the logic and efficiency of the server will also reduce the user experience.
- COMET
COMET technology improves the disadvantage of simple polling by using long polling. The long polling method on each request, the server side keeps the connection open for a period of time, rather than shutting down immediately after the response is completed. The advantage of this is that the data updates generated by the server can be returned to the browser in a timely manner during the time the connection is open. When the last long connection is closed, the browser will immediately open a new long connection to continue the request. However, the implementation of COMET technology requires third-party library support both on the server side and on the browser side.
Now, most of the Web app has Ajax, and that's what it looks like:
In a comprehensive comparison of the 4 different technologies mentioned above, simple polling is not recommended due to its own shortcomings. COMET technology is not part of the HTML 5 standard and is not recommended from a standards-compliant perspective. The WebSocket specification and server Push technology are all part of the HTML 5 standard and are recommended for native support on mainstream browsers. However, the WebSocket specification is more complex and is suitable for scenarios where complex bidirectional data communication is required. For simple server data push scenarios, using server push events is sufficient.
Based on data push, when the data source has new data, it is sent to the client immediately, without waiting for the client to request. These new data may be the most news, the latest stock quotes, chat information from friends, weather forecasts and so on.
Data pull and push function is the same, the user to get new data. But there are some advantages to data push. You may have heard of comet, Ajax push, reverse Ajax, HTTP streaming, WebSockets and SSE are different technologies. Perhaps the biggest advantage is low latency. SSE is used for Web applications to refresh data and does not require any action by the user.
WebSockets is a more complex technology to implement the server, but it is a true full-duplex socket, the server can push the data to the client, the client can also push the data back to the server. SSE works in existence HTTP/HTTPS protocol, support proxy server and authentication technology. SSE is a text protocol you can easily debug it. If you need to send large binary data from the service side to the client, WebSocket is a better choice.
Fortunately HTML5 provides us with a way: Server-sent events contains the new HTML element EventSource and the new MIME type Text/event-stream to complete my needs.
The server sends the event API, which is the EventSource interface, and you can specify a URI to accept the event while you create a new EventSource object. For example:
varnew EventSource("ssedemo.php");
<! DOCTYPE html><html><head> <title>Sever Sent Event Instance 1</title></head><body> <h2>Sever Sent Event Instance 1</H2> <div id="Result"></div> <script type="Text/javascript"> var result = document.getElementById (); if (typeof (EventSource)!== ' undefined ' ) {//Create Event source var Source = new EventSource ( ' test.php ' ); //listener event Source sent over data source.onmessage = function { result.innerhtml +=event.data + ; }}else {result.innerhtml + = "Your browser does not support server Sent Event "; } </script></body></html>
<?php //specifies the mime of the sending event stream as Text/event-stream header ( Content-type:text/event-stream ' ); //does not cache data sent by the server header ( ' Cache-control:no-cache ' ); //the event name sent by the specified server echo "event:test\n\n" ; //defines the data that the server sends to the client echo "Data: Server Current time:" . Date ( ' y-m-d h:i:s ' ). "\ n" ; //send data flow to client flush (); ?>
- Set the header "Content-type" to "Text/event-stream"
- No caching of pages is required
- Output send date (always start with "data:")
- Refresh output data to a Web page
Perhaps you should notice that PHP pushes the information one uses "\ n" as the end flag, after testing, if not "\ n" as the end flag, then the client will not be able to receive the push value. There is also a need to make a special statement: The message format of the push must be "data: Content \ n", otherwise ...
Event Stream Format
The event stream is just a simple text stream, and the text should be encoded in the UTF-8 format. Each message is followed by a blank line as a delimiter. The comment line, which begins with a colon, is ignored.
Each message is made up of multiple fields, each of which consists of a field name, a colon, and a field value.
Field
- Event
The event type. If the field is specified, when the client receives the message, an event is triggered on the current EventSource object, and the event type is the field value of the field, and you can use AddEventListener () The EventSource method listens for any type of named event on the current object, and if the message does not have an event field, it triggers the events handler on the OnMessage property.
- Data
The data field for the message. If the message contains more than one data field, the client uses a newline character to concatenate them into a string as the field value.
- ID
The event ID, which becomes the property value of the last event ID of the internal property of the current EventSource object.
- Retry
An integer value that specifies the time (in milliseconds) to reconnect, which is ignored if the field value is not an integer.
All other field names will be ignored except for the field names specified above. Chrome is pushed to the client every 3 seconds, and FF is pushed once every 5 seconds.
Note: If a line of text does not contain a colon, then the whole row is parsed into the field name and its field value is empty.
Standard events provided by the EventSource object
name |
Description |
Event Handling Methods |
Open |
Generated when a connection to the server is successfully established |
OnOpen |
Message |
Occurs when an event sent by the server is received |
OnMessage |
Error |
Generated when an error occurs |
OnError |
<! DOCTYPE html><html><head> <title>Sever Sent Event Instance 1</title></head><body> <h2>Sever Sent Event Instance 1</H2> <button onclick="closecnt ()">Disconnect Connection</button> <div id="Result"></div> <script type="Text/javascript"> varresult = document.getElementById (' Result ');if(typeof(EventSource)!==' undefined ') {//Create Event source varSource =NewEventSource (' test.php ');//Listen to the data sent by the event source .Source.onmessage = function(event){Result.innerhtml +=event.data +' <br> '; } Source.onopen = ConnectionOpen; Source.onclose = Connectionclose; function connectionopen(){ if(Source.readystate = =0) {result.innerhtml + =' connection not established <br> '; }if(Source.readystate = =1) {result.innerhtml + =' connected success <br> '; } } function connectionclose(){Result.innerhtml + ="Close the connection, the ReadyState property value is:"+ Source.readystate +' <br> '; } function closecnt(){Source.close (); Result.innerhtml + ="Disconnected, the ReadyState property value is:"+ Source.readystate +' <br> '; } }Else{result.innerhtml + ="Your browser does not support server sent Event"; }</script></body></html>
After you have created the EventSource object at the specified URL, you can add an event-handling method through the OnMessage and AddEventListener methods. When a new event is generated on the server side, the corresponding event handling method is called. The OnMessage property of the EventSource object acts like AddEventListener (' message '), but the OnMessage property supports only one event-handling method.
<! DOCTYPE html><html><head> <title>Sever Sent Event Instance 1</title></head><body> <h2>Sever Sent Event Instance 1</H2> <div id="Result"></div> <script type="Text/javascript"> varresult = document.getElementById (' Result ');if(typeof(EventSource)!==' undefined ') {//Create Event source varSource =NewEventSource (' test.php ');//Custom event source sent data, event name and PHP in the event name correspondingSource.addeventlistener (' MyEvent ',' updaterequests ',false);//Source.onmessage = function () { //result.innerhtml = Event.data + ' <br> '; // } function updaterequests(event){result.innerhtml = Event.data +' <br> '; } }Else{result.innerhtml + ="Your browser does not support server sent Event"; }</script></body></html>
<?php //指定发送事件流的MIME为text/event-stream header(‘Content-Type:text/event-stream‘); //不缓存服务端发送的数据 header(‘Cache-Control:no-cache‘); //指定服务器发送的事件名 echo "event:myevent\n\n"; // 定义服务器向客户端发送的数据 echo "data:服务器当前时间为:".date(‘Y-m-d H:i:s‘)."\n\n"; //向客户端发送数据流 flush(); ?>
The front end is HTML5, the backend can be PHP, JSP, node. js, ASP.
HTML5 Server Push Server-sent Event