Instant Messaging Development Technology SSE Detailed Explanation: HTML5 Server Push Event Technology

Generally speaking, web-side instant messaging technology is not easy to implement due to the design limitations of browsers. There are roughly four mainstream web-side instant messaging solutions: traditional Ajax short polling, Comet technology, and WebSocket technology. , SSE (Server-sent Events).

Server-sent Events, or SSE for short, is an integral part of the HTML 5 specification that can be used to push data from the server to the browser in real time. Compared with the similar COMET and WebSocket technologies, the use of server push events is simpler and the changes to the server side are relatively small. For some types of applications, server-push events are the best choice.

Most developers are no strangers to general web application development. In web applications, a request/response interaction model is used between the browser and the server. The browser sends a request, and the server generates a corresponding response according to the received request. The browser then processes the received response and displays it to the user. The format of the response may be HTML, XML or JSON, etc. With the popularity of the REST architectural style and AJAX, servers are increasingly using JSON as the data format for their responses. Web applications use the XMLHttpRequest object to send requests, and dynamically update the content of the page according to the data returned by the server. Typically, user actions on the page, such as clicking or moving the mouse, trigger corresponding events. The request is made by the XMLHttpRequest object, and the partial page update is performed after the server response is obtained. The disadvantage of this method is that the data changes generated on the server side cannot be notified to the browser in time, but can only be obtained by the browser when the next request is sent. For some applications that require high real-time data, this delay is unacceptable.

In order to meet the needs of such applications, there needs to be some way to push data from the server to the browser, so as to ensure that the data changes on the server can be notified to the user at the first time. There are many common solutions at present, which can be mainly divided into two categories. The difference between these two types of methods is whether they are implemented based on the HTTP protocol. The alternative to using the HTTP protocol is to use the new WebSocket specification in HTML 5, while the alternative to using the HTTP protocol includes simple polling, COMET technology, and the HTML 5 server-push events described in this article.

Before introducing HTML 5 server push events (SSE technology), 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, which has been supported by many mainstream browsers, and 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, and bidirectional data transmission can be performed. WebSocket is very powerful and flexible to use, and can be applied to different scenarios. However, the WebSocket technology is also more complex, including the implementation of the server side and the browser side, which are different from general Web applications.

In addition to WebSocket, other implementations are based on the HTTP protocol to achieve the effect of real-time push. The first method is simple polling, that is, the browser periodically sends a request 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, users will not be able to receive updated data in time; if the polling interval is too short, it will cause too many query requests and increase the burden on the server.

Comprehensively comparing the four different technologies mentioned above, simple polling is not recommended due to its own shortcomings. Comet technology is not part of the HTML 5 standard, nor is its use recommended from a standards-compliant perspective. Both the WebSocket specification and server push technology are part of the HTML 5 standard, and both provide native support on mainstream browsers and are recommended. However, the WebSocket specification is more complicated and is suitable for scenarios that require complex two-way data communication. For simple server data push scenarios, using server push (SSE technology) events is sufficient. Instant messaging chat software app development can add Weikeyun's v:weikeyyun24 consultation

 

 

In terms of browser support, Server Push Events (SSE technology) has been supported on most desktop and mobile browsers except IE. Browsers and versions that support server push events include: Firefox 6.0+, Chrome 6.0+, Safari 5.0+, Opera 11.0+, iOS Safari 4.0+, Opera Mobile 11.1+, Chrome for Android 25.0+, Firefox for Android 19.0+, and Blackberry Browser 7.0+ etc. The support of IE is described in detail in the following chapters.

Comparison with WebSocket

Simply put, SSE is suitable for frequent updates, low latency and data from server to client.

The difference between it and WebSocket:

    Convenience, no need to add any new components, you can continue to use it with any custom back-end language and framework, and you don't have to worry about getting a new IP or a new port number for a new virtual machine.
    Server-side simplicity. Because SSE works over existing HTTP/HTTPS protocols, it can run directly on existing proxy servers and authentication technologies.

The biggest advantage of WebSocket over SSE is that it is a two-way communication, which means that sending data from the server is as simple as receiving data from the server, while SSE generally transmits data from the client to the server through an independent Ajax request, so compared to Using Ajax with WebSocket adds overhead. Therefore, if you need to transmit data to the server at a frequency of once per second or faster, you should use WebSocket.

The technical specification and definition of SSE (Server-sent Events) in HTML 5

The Server-sent Events specification is an integral part of the HTML 5 specification, see Resources for specific specification documents. 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 object available to JavaScript on the browser side. 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 seen as an event stream, consisting 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 lines. Listing 1 shows an example of a server-side response.

SSE combat example: server-side and browser-side implementation

As can be seen from the description of the communication protocol in the previous section, the server-side push event is a relatively simple protocol. The implementation on the server side is also relatively simple. It only needs to return the response content according to the format specified by the protocol. Implementations corresponding to various server-side technologies can be found in the open source community. It is not difficult to develop it yourself. This article uses Java as the implementation language on the server side. The corresponding implementation is based on the open source jetty-eventsource-servlet project, see Resources. The following is a concrete example to illustrate how to use the jetty-eventsource-servlet project. The example is used to simulate the random movement of an object in a limited space. The object starts at a random position, then randomly chooses one of the four directions, up, down, left, and right, and moves a random distance in that direction. The server side continuously changes the position of the object, and pushes the position information to the browser, which is displayed by the browser.

Compatibility issues on IE

A big problem with using the browser's native EventSource object is that IE doesn't support it. To provide the same support on IE, there are generally two approaches. The first way is to use the native EventSource object on other browsers, and use simple polling or COMET technology on IE; the other way is to use polyfill technology, that is, use a JavaScript library provided by a third party to block browsing device is different. This article uses polyfill technology, which only needs to load third-party JavaScript libraries in the page. The browser-side code of the application itself does not need to be changed. The second approach is generally recommended, because in this case, only one implementation technique needs to be used on the server side.

Providing an implementation like a native EventSource object on IE is not straightforward. Theoretically speaking, it is only necessary to obtain the server-side response content through the XMLHttpRequest object, and through text parsing, the corresponding event can be extracted and the corresponding event processing method can be triggered. The problem, though, is that the XMLHttpRequest object on IE doesn't support getting partial response content. Only after the response is complete can its content be fetched. Because the server-side push event uses a long connection. When the connection is always open, the content of the response cannot be obtained through the XMLHttpRequest object, and the corresponding event cannot be triggered. More specifically, when the readyState of the XMLHttpRequest object is 3 (READYSTATE_INTERACTIVE), its responseText property cannot be obtained.

In order to solve the problem of XMLHttpRequest object on IE, it is necessary to use the XDomainRequest object introduced in IE 8. The role of the XDomainRequest object is to make cross-domain AJAX requests. The XDomainRequest object provides the onprogress event. When the onprogress event occurs, you can get the partial content of the response through the responseText property. This is the biggest difference between the XDomainRequest object and the XMLHttpRequest object, and it is also the basis for using the XDomainRequest object to implement a similar native EventSource object. After using the XDomainRequest object to open the connection with the server, when new data is generated on the server, it can be processed through the processing method of the onprogress event of the XDomainRequest object, parse the received data, and trigger the corresponding data according to the content of the data. event.

However, since the original purpose of the XDomainRequest object is to issue cross-domain AJAX requests, taking into account the security issues of cross-domain access, the XDomainRequest object has strict restrictions on its use. These limitations affect how it is implemented as an EventSource object. The specific limitations and workarounds are as follows:

    The server-side response needs to include the Access-Control-Allow-Origin header, which declares which domains are allowed to access the URL. "*" means that access from any domain is allowed, this value is deprecated. Generally use the same domain as the current application, and restrict access only from the current domain.
    The request issued by the XDomainRequest object cannot contain custom HTTP headers, which restricts the use of the Last-Event-ID header to declare the identifier of the last event received by the browser. This identifier may only be passed by other means of HTTP requests, such as parameters of a GET request or the body of a POST request.
    The content-type (Content-Type) of the request of the XDomainRequest object can only be "text/plain". This means that when a POST request is used, the framework used by the server, such as servlet, will not automatically parse the content of the POST request, and cannot use the getParameter method of the HttpServletRequest class to obtain the content of the POST request. Only the original request content can be parsed on the server side, and the values ​​of the parameters in it can be obtained.
    The request sent by the XDomainRequest object does not contain any information related to user authentication, including cookies and so on. This means that if authentication is required on the server side, the user's authentication information, such as session ID, needs to be passed through other HTTP requests.


Due to these limitations of the XDomainRequest object, the server-side implementation also needs to be changed accordingly. These changes include returning the Access-Control-Allow-Origin header; parsing the "text/plain" type parameters sent by the browser; processing user authentication-related information contained in the request.

Guess you like

Origin blog.csdn.net/wecloud1314/article/details/126503177