Server-sent Events (Server-sent Events) are a component of the HTML 5 specification and can be used to push data from the server to the browser in real time. Compared with similar COMET and WebSocket technologies, server push events are simpler to use and require less changes on the server side. For some types of applications, server push events are the best option.
WebSocket
Before introducing HTML 5 server push events, first introduce some of the server-side data push technologies mentioned above. The first is WebSocket. The WebSocket specification is an important part of HTML 5 and has been supported by many mainstream browsers. There are also many applications developed based on WebSocket. As the name suggests, WebSocket uses a socket connection, based on the TCP protocol. After using WebSocket, a socket connection is actually established between the server and the browser, allowing two-way data transmission. WebSocket is very powerful and flexible in use, and can be applied to different scenarios. However, WebSocket technology is also relatively complex, including server-side and browser-side implementations that are different from general Web applications.
Polling
In addition to WebSocket, other implementation methods are based on the HTTP protocol to achieve real-time push effects. The first method is simple polling, that is, the browser periodically sends requests to the server to check whether there is any data update. This approach is relatively simple and can solve the problem to a certain extent. However, the polling interval needs to be carefully considered. If the polling interval is too long, the user will not be able to receive updated data in time; if the polling interval is too short, it will lead to too many query requests and increase the burden on the server.
Disadvantages:
1: Polling is initiated by the client, so the server cannot determine whether the content I want to push has expired, because it is difficult for me to determine whether a certain information has expired. has been pushed to all clients, then the server needs to cache a large amount of data. If the data is stored in the database, then the database needs to be queried for every request, which is a big challenge for both database and system design.
2: The request frequency is too high, each request packet contains the same data, which may not be a big deal for PC, but for mobile clients, this Probably not the best solution. Especially when it comes to making permission judgments, the logic and efficiency of the server will also reduce the user experience.
COMET
COMET technology improves the shortcomings of simple polling and uses long polling. In the long polling method, the server will keep the connection open for a period of time during each request, instead of closing it immediately after the response is completed. The advantage of this is that during the period when the connection is open, data updates generated by the server can be returned to the browser in a timely manner. When the previous long connection is closed, the browser will immediately open a new long connection to continue the request. However, the implementation of COMET technology requires the support of third-party libraries on both the server side and the browser side.
Nowadays, most of the Web Apps have Ajax, which looks like this:
Comprehensive comparison of the four different technologies mentioned above, simple Polling is not recommended due to its inherent flaws. COMET technology is not part of the HTML 5 standard, and its use is not recommended from a standard-compliant perspective. The WebSocket specification and server push technology are both components of the HTML 5 standard. They provide native support in mainstream browsers and are recommended. However, the WebSocket specification is more complex and is suitable for scenarios that require complex two-way data communication. 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 request. This new data may be the latest news, latest stock quotes, chat messages from friends, weather forecasts, etc.
#The functions of data pull and push are the same, users get new data. But data push has some advantages. You may have heard that Comet, Ajax Push, Reverse Ajax, HTTP Streaming, WebSockets and SSE are different technologies. Probably the biggest advantage is low latency. SSE is used by web applications to refresh data without requiring any action from the user.
WebSockets is a more complex technology to implement the server, but it is a true full-duplex socket. The server can push data to the client, and the client can also push data back to the server. SSE works with the HTTP/HTTPS protocol and supports proxy servers and authentication technologies. SSE is a text protocol and you can easily debug it. If you need to send mostly binary data from server to 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-sent event API is the EventSource interface. When you create a new EventSource object, you can specify a URI that accepts events. For example:
var evtSource = new EventSource("ssedemo.php");
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //监听事件源发送过来的数据 source.onmessage = function(event){ result.innerHTML +=event.data +'<br>'; } }else{ result.innerHTML += "您的浏览器不支持server sent Event"; } </script></body></html>
<?php //指定发送事件流的MIME为text/event-stream header('Content-Type:text/event-stream'); //不缓存服务端发送的数据 header('Cache-Control:no-cache'); //指定服务器发送的事件名 echo "event:test\n\n"; // 定义服务器向客户端发送的数据 echo "data:服务器当前时间为:".date('Y-m-d H:i:s')."\n\n"; //向客户端发送数据流 flush(); ?>
Set the header "Content-Type" to "text/event-stream"
Specify that the page is not cached
Output sent date (always Starting with "data: ")
Refresh the output data to the web page
Perhaps everyone should notice that the information pushed by php is used "\n\n" is used as the end mark. After testing, if "\n\n" is not used as the end mark, the client will not be able to receive the pushed value. There is also a special statement that needs to be made: the pushed information format must be "data:content\n\n", otherwise. . .
The event stream is just a simple text data stream. The text should be encoded in UTF-8 format. Each message is followed by a space Lines serve as separators. Line comment lines starting with a colon will be ignored.
Each message is composed of multiple fields, and each field consists of a field name, a colon, and a field value.
Field
event
Event type. If this field is specified, the client receives the When a message is received, an event will be triggered on the current EventSource object. The event type is the field value of the field. You can use the addEventListener() method to listen for any type of named event on the current EventSource object. If the message does not have an event field , the event processing function on the onmessage attribute will be triggered.
data
The data field of the message. If the message contains multiple data fields, then The client will use newlines to concatenate them into a string as the field value.
id
Event ID will become the internal part of the current EventSource object The attribute value of the attribute "Last Event ID".
retry
An integer value that specifies the reconnection time (in milliseconds), if If the field value is not an integer, it will be ignored.
Except for the field names specified above, all other field names will be ignored. Chrome pushes to the client every 3 seconds, while FF pushes every 5 seconds.
Note: If a line of text does not contain a colon, the entire line of text will be parsed into a field name, and its field value will be empty.
EventSource object Provided standard events
Name | Description | Event handling method |
---|---|---|
open | Produced when a connection is successfully established with the server | onopen |
message | When received | onmessage |
error | generated when an error occurs | onerror |
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <button onclick="closeCnt()">断开连接</button> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //监听事件源发送过来的数据 source.onmessage = function(event){ result.innerHTML +=event.data +'<br>'; } source.onopen = connectionOpen; source.onclose = connectionClose; function connectionOpen(){ if (source.readyState == 0) { result.innerHTML +='未建立连接<br>'; } if (source.readyState == 1) { result.innerHTML +='连接成功<br>'; } } function connectionClose(){ result.innerHTML += "关闭连接,readyState属性值为:" + source.readyState + '<br>'; } function closeCnt(){ source.close(); result.innerHTML += "断开连接,readyState属性值为:" + source.readyState + '<br>'; } }else{ result.innerHTML += "您的浏览器不支持server sent Event"; } </script></body></html>
在指定 URL 创建出 EventSource 对象之后,可以通过 onmessage 和 addEventListener 方法来添加事件处理方法。当服务器端有新的事件产生,相应的事件处理方法会被调用。EventSource 对象的 onmessage 属性的作用类似于 addEventListener( ‘ message ’ ),不过 onmessage 属性只支持一个事件处理方法。
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //自定义事件源发送过来的数据,事件名和php中事件名对应 source.addEventListener('myevent', 'updateRequests', false); // source.onmessage = function() { // result.innerHTML = event.data + '<br>'; // } function updateRequests(event){ result.innerHTML = event.data + '<br>'; } }else{ result.innerHTML += "您的浏览器不支持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(); ?>
前端是HTML5,后端可以是PHP, JSP, Node.js, Asp.net等应用。
服务器推送事件(Server-sent Events)是 HTML 5 规范中的一个组成部分,可以用来从服务端实时推送数据到浏览器端。相对于与之类似的 COMET 和 WebSocket 技术来说,服务器推送事件的使用更简单,对服务器端的改动也比较小。对于某些类型的应用来说,服务器推送事件是最佳的选择。
WebSocket
在介绍 HTML 5 服务器推送事件之前,首先介绍一些上面提到的几种服务器端数据推送技术。第一种是 WebSocket。WebSocket 规范是 HTML 5 中的一个重要组成部分,已经被很多主流浏览器所支持,也有不少基于 WebSocket 开发的应用。正如名称所表示的一样,WebSocket 使用的是套接字连接,基于 TCP 协议。使用 WebSocket 之后,实际上在服务器端和浏览器之间建立一个套接字连接,可以进行双向的数据传输。WebSocket 的功能是很强大的,使用起来也灵活,可以适用于不同的场景。不过 WebSocket 技术也比较复杂,包括服务器端和浏览器端的实现都不同于一般的 Web 应用。
轮询
除了 WebSocket 之外,其他的实现方式是基于 HTTP 协议来达到实时推送的效果。第一种做法是简易轮询,即浏览器端定时向服务器端发出请求,来查询是否有数据更新。这种做法比较简单,可以在一定程度上解决问题。不过对于轮询的时间间隔需要进行仔细考虑。轮询的间隔过长,会导致用户不能及时接收到更新的数据;轮询的间隔过短,会导致查询请求过多,增加服务器端的负担。
缺点:
1:轮询是由客户端发起的,那么在服务端就不能判别我要推送的内容是否已经过期,因为我很难判断某个信息是否已经推送给全部的客户端,那么服务端就需要缓存大量的数据。如果数据保存在数据库,那么还要每次请求都需要查询数据库,这对数据库和系统设计都是一个很大的挑战。
2:请求的频率太高,每次的请求包中含有同样的数据,这对pc来说也许算不得什么,但是对于移动客户端来讲,这应该不是最佳的方案。尤其是遇到还要做权限判断的时候,那么服务端的逻辑和效率也会造成用户体验的降低。
COMET
COMET 技术改进了简易轮询的缺点,使用的是长轮询。长轮询的方式在每次请求时,服务器端会保持该连接在一段时间内处于打开状态,而不是在响应完成之后就立即关闭。这样做的好处是在连接处于打开状态的时间段内,服务器端产生的数据更新可以被及时地返回给浏览器。当上一个长连接关闭之后,浏览器会立即打开一个新的长连接来继续请求。不过 COMET 技术的实现在服务器端和浏览器端都需要第三方库的支持。
现在Web App中,大都有Ajax,是这样子:
综合比较上面提到的 4 种不同的技术,简易轮询由于其本身的缺陷,并不推荐使用。COMET 技术并不是 HTML 5 标准的一部分,从兼容标准的角度出发,也不推荐使用。WebSocket 规范和服务器推送技术都是 HTML 5 标准的组成部分,在主流浏览器上都提供了原生的支持,是推荐使用的。不过 WebSocket 规范更加复杂一些,适用于需要进行复杂双向数据通讯的场景。对于简单的服务器数据推送的场景,使用服务器推送事件就足够了。
基于数据推送是这样的,当数据源有新数据,它马上发送到客户端,不需要等待客户端请求。这些新数据可能是最新闻,最新股票行情,来自朋友的聊天信息,天气预报等。
数据拉与推的功能是一样的,用户拿到新数据。但数据推送有一些优势。 你可能听说过Comet, Ajax推送, 反向Ajax, HTTP流,WebSockets与SSE是不同的技术。可能最大的优势是低延迟。SSE用于web应用程序刷新数据,不需要用户做任何动作。
WebSockets is a more complex technology to implement the server, but it is a true full-duplex socket. The server can push data to the client, and the client can also push data back to the server. SSE works with the HTTP/HTTPS protocol and supports proxy servers and authentication technologies. SSE is a text protocol and you can easily debug it. If you need to send mostly binary data from server to 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-sent event API is the EventSource interface. When you create a new EventSource object, you can specify a URI that accepts events. For example:
var evtSource = new EventSource("ssedemo.php");
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //监听事件源发送过来的数据 source.onmessage = function(event){ result.innerHTML +=event.data +'<br>'; } }else{ result.innerHTML += "您的浏览器不支持server sent Event"; } </script></body></html>
<?php //指定发送事件流的MIME为text/event-stream header('Content-Type:text/event-stream'); //不缓存服务端发送的数据 header('Cache-Control:no-cache'); //指定服务器发送的事件名 echo "event:test\n\n"; // 定义服务器向客户端发送的数据 echo "data:服务器当前时间为:".date('Y-m-d H:i:s')."\n\n"; //向客户端发送数据流 flush(); ?>
Set the header "Content-Type" to "text/event-stream"
Specify that the page is not cached
Output sent date (always Starting with "data: ")
Refresh the output data to the web page
Perhaps everyone should notice that the information pushed by php is used "\n\n" is used as the end mark. After testing, if "\n\n" is not used as the end mark, the client will not be able to receive the pushed value. There is also a special statement that needs to be made: the pushed information format must be "data:content\n\n", otherwise. . .
The event stream is just a simple text data stream. The text should be encoded in UTF-8 format. Each message is followed by a space Lines serve as separators. Line comment lines starting with a colon will be ignored.
Each message is composed of multiple fields, and each field consists of a field name, a colon, and a field value.
Field
event
Event type. If this field is specified, the client receives the When a message is received, an event will be triggered on the current EventSource object. The event type is the field value of the field. You can use the addEventListener() method to listen for any type of named event on the current EventSource object. If the message does not have an event field , the event processing function on the onmessage attribute will be triggered.
data
The data field of the message. If the message contains multiple data fields, then The client will use newlines to concatenate them into a string as the field value.
id
Event ID will become the internal part of the current EventSource object The attribute value of the attribute "Last Event ID".
retry
An integer value that specifies the reconnection time (in milliseconds), if If the field value is not an integer, it will be ignored.
Except for the field names specified above, all other field names will be ignored. Chrome pushes to the client every 3 seconds, while FF pushes every 5 seconds.
Note: If a line of text does not contain a colon, the entire line of text will be parsed into a field name, and its field value will be empty.
EventSource object Provided standard events
Name | Description | Event handling method |
---|---|---|
open | Produced when a connection is successfully established with the server | onopen |
message | When received | onmessage |
error | generated when an error occurs | onerror |
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <button onclick="closeCnt()">断开连接</button> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //监听事件源发送过来的数据 source.onmessage = function(event){ result.innerHTML +=event.data +'<br>'; } source.onopen = connectionOpen; source.onclose = connectionClose; function connectionOpen(){ if (source.readyState == 0) { result.innerHTML +='未建立连接<br>'; } if (source.readyState == 1) { result.innerHTML +='连接成功<br>'; } } function connectionClose(){ result.innerHTML += "关闭连接,readyState属性值为:" + source.readyState + '<br>'; } function closeCnt(){ source.close(); result.innerHTML += "断开连接,readyState属性值为:" + source.readyState + '<br>'; } }else{ result.innerHTML += "您的浏览器不支持server sent Event"; } </script></body></html>
在指定 URL 创建出 EventSource 对象之后,可以通过 onmessage 和 addEventListener 方法来添加事件处理方法。当服务器端有新的事件产生,相应的事件处理方法会被调用。EventSource 对象的 onmessage 属性的作用类似于 addEventListener( ‘ message ’ ),不过 onmessage 属性只支持一个事件处理方法。
<!DOCTYPE html><html><head> <title>sever Sent Event实例1</title></head><body> <h2>sever Sent Event实例1</h2> <p id="result"></p> <script type="text/javascript"> var result = document.getElementById('result'); if (typeof (EventSource) !== 'undefined') { //创建事件源 var source = new EventSource('test.php'); //自定义事件源发送过来的数据,事件名和php中事件名对应 source.addEventListener('myevent', 'updateRequests', false); // source.onmessage = function() { // result.innerHTML = event.data + '<br>'; // } function updateRequests(event){ result.innerHTML = event.data + '<br>'; } }else{ result.innerHTML += "您的浏览器不支持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(); ?>
前端是HTML5,后端可以是PHP, JSP, Node.js, Asp.net等应用。
以上就是Html5 服务端推送 Server-Sent Event的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!