In various BS architecture applications, it is often expected that the server can actively push various messages to the client to achieve notifications such as emails, messages, to-do items, etc.
The problem with the BS architecture itself is that the server has always used a question-and-answer mechanism. This means that if the client does not actively send messages to the server , the server has no way of knowing how to push messages to the client.
With the development of various technologies and standards such as HTML and browsers, different means and methods have been generated to enable the server to actively push messages. They are: AJAX, Comet, ServerSent and WebSocket.
This article will provide a straightforward explanation of the various technical methods mentioned above.
AJAX
A normal page works like this in the browser:
The user gives the browser an address that needs to be accessed
The browser accesses the server based on this address and creates a TCP connection (HTTP request) with the server
The server constructs a piece of HTML text based on this address and some other data, and writes it into the TCP connection , and then close the connection
The browser gets the HTML text from the server, parses and presents it to the browser for the user to browse
At this time, the user clicks on any on the website Or when any
The browser uses the parameters of the form or the parameters of a as the access address
Creates a TCP connection with the server
Server Form HTML text, and then close the connection
The browser destroys the currently displayed page and presents a new page to the user according to the new HTML text
It is not difficult for us to find that the middle of the whole process , once a connection is established, the page cannot be maintained. The whole process seems a bit forceful. Maybe I just want a new Coke, but you insist on giving me the entire package.
At this point we can take a look at the XmlHttpRequest component. This component allows us to manually create an HTTP request and send the data we want. The server can also only return the results we want. The biggest benefit is that when we When receiving the response from the server, the original page is not destroyed. It's like, I shouted "I've finished my coffee, I want a refill", and then the waiter brought me a cup of coffee instead of throwing away all the unfinished set meals.
When we use AJAX to implement server push, the essence is that the client keeps asking the server "Is there any message for me?", and then the server answers "yes" or "no" to achieve this. achieve results. Its implementation method is also very simple. It is also very convenient to use the AJAX call encapsulated by the jQuery framework:
function getMessage(fn) { $.ajax({ url: "Handler.ashx", //一个能够提供消息的页面 dataType: "text", //响应类型,可以是JSON,XML等其它类型 type: "get", //HTTP请求类型,还可以是post success: function (d, s) { fn(d); //得到了正常的响应时,利用回调函数通知外部 }, complete: function (x, s) { setTimeout(function () { getMessage(fn); }, 5000); //无论响应成功或失败,在若干秒后再询问一次服务器 } }); }
Through the above code, you can ask the server every 5 seconds whether there are messages that need to be processed. Through this The method can achieve the effect of push, but there will be a problem:
The faster the interval, the better the timeliness of push, and the greater the consumption of the server;
The slower the interval, the more timely push The lower the timeliness, the smaller the server consumption.
And strictly speaking, this actual method is not a real server actively pushing messages, but due to the lack of early technical means, AJAX round robin has become a very common method.
The following is a detailed description of the specifications of server push events.
Specification
Server-sent Events specification is an integral part of the HTML 5 specification. For specific specification documents, see reference resources. The specification is relatively simple and mainly consists of two parts: the first part is the communication protocol between the server side and the browser side, and the second part is the EventSource that can be used by JavaScript on the browser side. object. The communication protocol is a simple protocol based on plain text. The content type of the server-side response is "text/event-stream". The content of the response text can be viewed as an event stream, composed of different events. Each event consists of two parts: type and data, and each event can have an optional identifier. The contents of different events are separated by blank lines ("\r\n") containing only carriage returns and line feeds. The data for each event may consist of multiple rows. Code Listing 1 gives an example of a server-side response.
Example of server-side response
data: first event data: second event id: 100 event: myevent data: third event id: 101 : this is a comment data: fourth event data: fourth event continue
As shown in the code listing 1, each event is separated by a blank line . For each line, the colon (":") before it indicates the type of the line, and the colon after it indicates the corresponding value. Possible types include:
The type is blank, indicating that the line is a comment and will be ignored during processing.
The type is data, indicating that the row contains data. Lines starting with data can appear multiple times. All these rows are data for that event.
The type is event, indicating the type of event used by this line to declare the event. When the browser receives data, it will generate events of the corresponding type.
The type is id, indicating the identifier used by this row to declare the event.
The type is retry, which means that this line is used to declare the waiting time of the browser before reconnecting after the connection is disconnected.
In the above code, the first event only contains the data "first event" and a default event will be generated; the identifier of the second event is 100 and the data is "second event "; The third event will generate an event of type "myevent"; the data of the last event is "fourth event\nfourth event continue". When there are multiple rows of data, the actual data is formed by concatenating each row of data with newline characters.
If the data returned by the server contains the event identifier, the browser will record the identifier of the most recently received event. If the connection to the server is interrupted, when the browser connects again, the identifier of the last received event will be declared through the HTTP header "Last-Event-ID". The server side can determine which event to start from to continue the connection through the event identifier sent by the browser side.
For the response returned by the server, the browser needs to use the EventSource object in JavaScript to process it. EventSource uses the standard event listener method. You only need to add the corresponding event processing method on the object. EventSource provides three standard events, as shown in Table 1.
Table 1. Standard events provided by EventSource objects
Name | Description | Event handling method |
open | When | onopen |
##message | ## is generated when a connection to the server is successfully established. #Occurs when an event sent by the server is received##onmessage | ##error |
Generated when an error occurs | onerror | 如之前所述,服务器端可以返回自定义类型的事件。对于这些事件,可以使用 addEventListener 方法来添加相应的事件处理方法。代码清单 2 给出了 EventSource 对象的使用示例。 EventSource 对象的使用示例 var es = new EventSource('events'); es.onmessage = function(e) { console.log(e.data); }; es.addEventListener('myevent', function(e) { console.log(e.data); }); Copy after login 如上所示,在指定 URL 创建出 EventSource 对象之后,可以通过 onmessage 和 addEventListener 方法来添加事件处理方法。当服务器端有新的事件产生,相应的事件处理方法会被调用。EventSource 对象的 onmessage 属性的作用类似于 addEventListener( ‘ message ’ ),不过 onmessage 属性只支持一个事件处理方法。在介绍完服务器推送事件的规范内容之后,下面介绍服务器端的实现。 服务器端和浏览器端实现 从上一节中对通讯协议的描述可以看出,服务器端推送事件是一个比较简单的协议。服务器端的实现也相对比较简单,只需要按照协议规定的格式,返回响应内容即可。在开源社区可以找到各种不同的服务器端技术相对应的实现。自己开发的难度也不大。本文使用 Java 作为服务器端的实现语言。相应的实现基于开源的 jetty-eventsource-servlet 项目,见参考资源。下面通过一个具体的示例来说明如何使用 jetty-eventsource-servlet 项目。示例用来模拟一个物体在某个限定空间中的随机移动。该物体从一个随机位置开始,然后从上、下、左和右四个方向中随机选择一个方向,并在该方向上移动随机的距离。服务器端不断改变该物体的位置,并把位置信息推送给浏览器,由浏览器来显示。 服务器端实现 服务器端的实现由两部分组成:一部分是用来产生数据的 org.eclipse.jetty.servlets.EventSource 接口的实现,另一部分是作为浏览器访问端点的继承自 org.eclipse.jetty.servlets.EventSourceServlet 类的 servlet 实现。下面代码给出了 EventSource 接口的实现类。 EventSource 接口的实现类 MovementEventSource public class MovementEventSource implements EventSource { private int width = 800; private int height = 600; private int stepMax = 5; private int x = 0; private int y = 0; private Random random = new Random(); private Logger logger = Logger.getLogger(getClass().getName()); public MovementEventSource(int width, int height, int stepMax) { this.width = width; this.height = height; this.stepMax = stepMax; this.x = random.nextInt(width); this.y = random.nextInt(height); } @Override public void onOpen(Emitter emitter) throws IOException { query(emitter); //开始生成位置信息 } @Override public void onResume(Emitter emitter, String lastEventId) throws IOException { updatePosition(lastEventId); //更新起始位置 query(emitter); //开始生成位置信息 } //根据Last-Event-Id来更新起始位置 private void updatePosition(String id) { if (id != null) { String[] pos = id.split(","); if (pos.length > 1) { int xPos = -1, yPos = -1; try { xPos = Integer.parseInt(pos[0], 10); yPos = Integer.parseInt(pos[1], 10); } catch (NumberFormatException e) { } if (isValidMove(xPos, yPos)) { x = xPos; y = yPos; } } } } private void query(Emitter emitter) throws IOException { emitter.comment("Start sending movement information."); while(true) { emitter.comment(""); move(); //移动位置 String id = String.format("%s,%s", x, y); emitter.id(id); //根据位置生成事件标识符 emitter.data(id); //发送位置信息数据 try { Thread.sleep(2000); } catch (InterruptedException e) { logger.log(Level.WARNING, \ "Movement query thread interrupted. Close the connection.", e); break; } } emitter.close(); //当循环终止时,关闭连接 } @Override public void onClose() { } //获取下一个合法的移动位置 private void move() { while (true) { int[] move = getMove(); int xNext = x + move[0]; int yNext = y + move[1]; if (isValidMove(xNext, yNext)) { x = xNext; y = yNext; break; } } } //判断当前的移动位置是否合法 private boolean isValidMove(int x, int y) { return x >= 0 && x <= width && y >=0 && y <= height; } //随机生成下一个移动位置 private int[] getMove() { int[] xDir = new int[] {-1, 0, 1, 0}; int[] yDir = new int[] {0, -1, 0, 1}; int dir = random.nextInt(4); return new int[] {xDir[dir] * random.nextInt(stepMax), \ yDir[dir] * random.nextInt(stepMax)}; } } Copy after login 类 MovementEventSource 需要实现 EventSource 接口的 onOpen、onResume 和 onClose 方法,其中 onOpen 方法在浏览器端的连接打开的时候被调用,onResume 方法在浏览器端重新建立连接时被调用,onClose 方法则在浏览器关闭连接的时候被调用。onOpen 和 onResume 方法都有一个 EventSource.Emitter 接口类型的参数,可以用来发送数据。EventSource.Emitter 接口中包含的方法包括 data、event、comment、id 和 close 等,分别对应于通讯协议中各种不同类型的事件。而 onResume 方法还额外包含一个参数 lastEventId,表示通过 Last-Event-ID 头发送过来的最近一次事件的标识符。 MovementEventSource 类中事件生成的主要逻辑在 query 方法中。该方法中包含一个无限循环,每隔 2 秒钟改变一次位置,同时把更新之后的位置通过 EventSource.Emitter 接口的 data 方法发送给浏览器端。每个事件都有对应的标识符,而标识符的值就是位置本身。如果连接断开之后,浏览器重新进行连接,可以从上一次的位置开始继续移动该物体。 与 MovementEventSource 类对应的 servlet 实现比较简单,只需要继承自 EventSourceServlet 类并覆写 newEventSource 方法即可。在 newEventSource 方法的实现中,需要返回一个 MovementEventSource 类的对象,如下所示。每当浏览器端建立连接时,该 servlet 会创建一个新的 MovementEventSource 类的对象来处理该请求。 servlet 实现类 MovementServlet public class MovementServlet extends EventSourceServlet { @Override protected EventSource newEventSource(HttpServletRequest request, String clientId) { return new MovementEventSource(800, 600, 20); } } Copy after login 在服务器端实现中,需要注意的是要添加相应的 servlet 过滤器支持。这是 jetty-eventsource-servlet 项目所依赖的 Jetty Continuations 框架的要求,否则的话会出现错误。添加过滤器的方式是在 web.xml 文件中添加代码如下所示的配置内容。 Jetty Continuations 所需 servlet 过滤器的配置 <filter> <filter-name>continuation</filter-name> <filter-class>org.eclipse.jetty.continuation.ContinuationFilter</filter-class> </filter> <filter-mapping> <filter-name>continuation</filter-name> <url-pattern>/sse/*</url-pattern> </filter-mapping> Copy after login 浏览器端实现 浏览器端的实现也比较简单,只需要创建出 EventSource 对象,并添加相应的事件处理方法即可。下面代码给出了相应的实现。在页面中使用一个方块表示物体。当接收到新的事件时,根据事件数据中给出的坐标信息,更新方块在页面上的位置。 浏览器端的实现代码 var es = new EventSource('sse/movement'); es.addEventListener('message', function(e) { var pos = e.data.split(','), x = pos[0], y = pos[1]; $('#box').css({ left : x + 'px', top : y + 'px' }); }); Copy after login 在介绍完基本的服务器端和浏览器端实现之后,下面介绍比较重要的 IE 的支持。 IE 支持 使用浏览器原生的 EventSource 对象的一个比较大的问题是 IE 并不提供支持。为了在 IE 上提供同样的支持,一般有两种办法。第一种办法是在其他浏览器上使用原生 EventSource 对象,而在 IE 上则使用简易轮询或 COMET 技术来实现;另外一种做法是使用 polyfill 技术,即使用第三方提供的 JavaScript 库来屏蔽浏览器的不同。本文使用的是 polyfill 技术,只需要在页面中加载第三方 JavaScript 库即可。应用本身的浏览器端代码并不需要进行改动。一般推荐使用第二种做法,因为这样的话,在服务器端只需要使用一种实现技术即可。 在 IE 上提供类似原生 EventSource 对象的实现并不简单。理论上来说,只需要通过 XMLHttpRequest 对象来获取服务器端的响应内容,并通过文本解析,就可以提取出相应的事件,并触发对应的事件处理方法。不过问题在于 IE 上的 XMLHttpRequest 对象并不支持获取部分的响应内容。只有在响应完成之后,才能获取其内容。由于服务器端推送事件使用的是一个长连接。当连接一直处于打开状态时,通过 XMLHttpRequest 对象并不能获取响应的内容,也就无法触发对应的事件。更具体的来说,当 XMLHttpRequest 对象的 readyState 为 3(READYSTATE_INTERACTIVE)时,其 responseText 属性是无法获取的。 为了解决 IE 上 XMLHttpRequest 对象的问题,就需要使用 IE 8 中引入的 XDomainRequest 对象。XDomainRequest 对象的作用是发出跨域的 AJAX 请求。XDomainRequest 对象提供了 onprogress 事件。当 onprogress 事件发生时,可以通过 responseText 属性来获取到响应的部分内容。这是 XDomainRequest 对象和 XMLHttpRequest 对象的最大不同,也是使用 XDomainRequest 对象来实现类似原生 EventSource 对象的基础。在使用 XDomainRequest 对象打开与服务器端的连接之后,当服务器端有新的数据产生时,可以通过 XDomainRequest 对象的 onprogress 事件的处理方法来进行处理,对接收到的数据进行解析,根据数据的内容触发相应的事件。 不过由于 XDomainRequest 对象本来的目的是发出跨域 AJAX 请求,考虑到跨域访问的安全性问题,XDomainRequest 对象在使用时的限制也比较严格。这些限制会影响到其作为 EventSource 对象的实现方式。具体的限制和解决办法如下所示:
由于 XDomainRequest 对象的这些限制,服务器端的实现也需要作出相应的改动。这些改动包括返回 Access-Control-Allow-Origin 头;对于浏览器端发送的“text/plain”类型的参数进行解析;处理请求中包含的用户认证相关的信息。 本文的示例使用的 polyfill 库是 GitHub 上的 Yaffle 开发的 EventSource 项目,具体的地址见参考资源。在使用该 polyfill 库,并对服务器端的实现进行修改之后,就可以在 IE 8 及以上的浏览器中使用服务器推送事件。如果需要支持 IE 7,则只能使用简易轮询或 COMET 技术。本文的示例代码见参考资源。 小结 If you need to push data from the server to the browser, technologies based on the HTML 5 specification standard that can be used include WebSocket and server push events. Developers can choose the appropriate technology based on their application's specific needs. If you just need to push data from the server side, the specification of server push events is simpler and easier to implement. This article provides a detailed introduction to the specification content of server push events, server-side and browser-side implementations, and also conducts a detailed analysis of how to support IE browsers. The above is the detailed content of Detailed introduction to html5 server push. For more information, please follow other related articles on the PHP Chinese website!
Previous article:How to use HTML5 geo-targeting feature?
Next article:Detailed explanation on the use of volume attribute in html5
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Can PDF files run HTML5 and Javascript?
I have a stupid idea to try and make a program that won't be blocked on any computer since...
From 2024-04-05 12:57:00
0
1
456
Make the page mobile-friendly?
I have many web pages and some websites. The thing is, I'm a beginner. I'm using basic htm...
From 2024-04-01 20:42:38
0
1
259
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
|