Websocket actual combat — turn

Original address: http://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/

As we all know, the interaction process of web applications is usually that the client sends a request through the browser, the server receives the request, processes it and returns the results to the client, and the client browser presents the information. This mechanism is acceptable for applications with less frequent information changes, but it is difficult for applications with high real-time requirements and massive concurrency, Especially in the current trend of vigorous development of mobile Internet in the industry, high concurrency and user real-time response are common problems faced by web applications, such as real-time information of financial securities, geographic location acquisition in web navigation applications, real-time message push of social networks, etc. When dealing with such business scenarios, the traditional request response web development usually adopts real-time communication scheme. The common is polling. The principle is simple and easy to understand, that is, the client sends requests to the server in the form of frequent requests at a certain time interval to keep the data synchronization between the client and the server. The problem is obvious. When the client sends requests to the server at a fixed frequency, the data on the server may not be updated, resulting in a lot of unnecessary requests, waste of bandwidth and low efficiency. Based on flash, Adobe Flash completes data exchange through its own socket, and then uses flash to expose that the corresponding interface is called by JavaScript, so as to achieve the purpose of real-time transmission. This method is more efficient than polling, and because of the high installation rate of flash and a wide range of application scenarios, Flash support is not good on mobile Internet terminals. There is no flash in the IOS system. Although flash is supported in Android, the actual use effect is not satisfactory, and there are high requirements for the hardware configuration of mobile devices. In 2012, Adobe officially announced that it would no longer support Android 4 1 + system, announcing the death of flash on the mobile terminal. As can be seen from the above, the traditional web model will encounter insurmountable bottlenecks when dealing with high concurrency and real-time requirements. We need an efficient and energy-saving two-way communication mechanism to ensure the real-time transmission of data. In this context, websocket, which is based on HTML5 specification and known as web TCP, came into being. In the early days, HTML5 did not form a unified specification in the industry, and various browser and application server manufacturers had different similar implementations, such as IBM's mqtt and comet open source framework. Until 2014, HTML5 was finally implemented from the draft to the actual standard specification with the promotion and cooperation of giants such as IBM, Microsoft and Google, Various application server and browser manufacturers have gradually begun to unify, and the websocket protocol has also been implemented in Java ee7. Therefore, the WebSockets on both the client and the server are complete. Readers can consult and be familiar with the new HTML protocol specification and websocket support. The following is a brief introduction to the principle and operation mechanism of websocket. Websocket is a new protocol of HTML5. It realizes the full duplex communication between the browser and the server, which can better save server resources and bandwidth and achieve real-time communication. It is based on TCP and transmits data through TCP like HTTP, but its biggest difference from HTTP is that websocket is a two-way communication protocol. After the connection is established, Websocket server and browser / client agent can actively send or receive data to each other, just like socket; Websocket requires a TCP like client and server to connect through handshake. Only after the connection is successful can they communicate with each other. The interaction between the traditional HTTP client and server in non websocket mode is shown in the following figure: the interaction between the client and server in websocket mode is shown in the following figure: the comparison of the above figure shows that compared with the traditional HTTP mode in which the client and server need to establish a connection for each request response, websocket is a communication mode similar to the TCP long connection of socket, Once the websocket connection is established, the subsequent data is transmitted in the form of frame sequence. Before the client disconnects the websocket connection or the server disconnects, the client and the server do not need to re initiate the connection request. In the case of massive concurrency and large interactive load traffic between the client and the server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages. Moreover, the client sends and receives messages on the same persistent connection, which has obvious real-time advantages. Let's look at the difference between websocket communication and traditional HTTP through the interactive messages between the client and the server: on the client, new websocket instantiates a new websocket client object and connects the websocket URL of the server similar to WS: / / yourdomain: port / path. The websocket client object will be automatically resolved and recognized as a websocket request, Thus, connect to the server port and execute the handshake process. The data format sent by the client is similar: it can be seen that the websocket connection message initiated by the client is similar to the traditional HTTP message. "Upgrade: websocket" parameter value indicates that this is a websocket type request, "sec websocket key" is a Base64 encoded ciphertext sent by the websocket client, The server must return a corresponding encrypted "sec websocket accept" response, otherwise the client will throw an "error during websocket handshake" error and close the connection. The data format returned by the server after receiving the message is similar: "sec websocket accept" is calculated by the server using the same key as the client and returned to the client. "Http / 1.1 101 switching protocols" means that the server accepts the client connection of websocket protocol. After such request response processing, After the websocket connection handshake of the client and server is successful, TCP communication can be carried out later. Readers can learn more about the interactive data format of websocket client and server. In terms of development, the websocket API is also very simple. We only need to instantiate the websocket and create a connection, and then the server and client can send and respond to each other. In the websocket implementation and case analysis section below, we can see the detailed websocket API and code implementation. As mentioned above, the implementation of websocket is divided into client and server, client (usually the browser) sends out a websocket connection request, and the server responds to it, realizing an action similar to TCP handshake, so as to form an HTTP long connection fast channel between the browser client and the websocket server. The subsequent direct data transmission between the two is carried out, and there is no need to initiate a connection and corresponding. The following briefly describes the websocket server API and client Client API. Websocket server has been basically supported by API conforming to Jee jsr356 standard among mainstream application server manufacturers (for details), the following lists the support of some common commercial and open source application servers for the websocket server side: below, we use Tomcat 7.0.5 server side example code to illustrate the implementation of the websocket server side: the websocket specification of jsr356 uses the API of javax. Websocket. *, which can integrate a common Java object (POJO) use the @ serverendpoint annotation as the endpoint of the websocket server. The code example is as follows: @ onopen public void onopen (session) throws IOException {/ / the following code is omitted...}@ Onmessage public string onmessage (string message) {/ / the following code is omitted...}@ Message (maxmessagesize = 6) public void receivemessage (string s) {/ / the following code is omitted...}@ Onerror public void onerror (throwable T) {/ / the following code is omitted...}@ Onclose public void onclose (session, closereason) {/ / the following code is omitted...}} Code explanation: the concise code above establishes a websocket server. The annotation endpoint of @ serverendpoint ("/ echo") indicates that the websocket server runs at the access endpoint of WS: / / [server IP or domain name]: [server port] / WebSockets / echo. The client browser can initiate a long http connection to the websocket client API. The class annotated with serverendpoint must have a public parameterless constructor. The Java method annotated with @ onmessage is used to receive the incoming websocket information, which can be in text format or binary format. Onopen is called when a new connection is established at this endpoint. Parameter provides more details about the other end of the connection. Session indicates the other end of the conversation connection between two websocket endpoints, which can be understood as a concept similar to HTTP session. Onclose is called when the connection is terminated. The parameter closereason encapsulates more details, such as why a websocket connection is closed. For more advanced customization, such as @ message annotation, maxmessagesize property can be used to define the maximum limit of message bytes. In the example program, if more than 6 bytes of information are received, an error will be reported and the connection will be closed. Note: WebSockets supported by different application servers in the early stage are different. Even if the same manufacturer, there are slight differences between different versions, such as Tomcat Server 7.0 The versions above 5 are implemented by the standard jsr356 specification, while 7.0 2x/7.0. Versions of 3x use custom APIs (websocketservlet and streaminbound, the former is a container used to initialize the websocket environment; the latter is used to specifically process websocket requests and responses, see the case analysis section for details). Moreover, Tomcat 7.0.3x has different definitions from 7.0.2x's createwebsocketinbound method, and an HttpServletRequest parameter is added, so that it can be obtained from the request parameter More information about websocket client is shown in the following code: therefore, the server side of websocket needs to select its version. Generally, the support of the updated version for websocket is the standard JSR specification API, but the development ease of use and the portability of old version programs should also be considered, as shown in the customer case described below, Tomcat 7.0 is used because the customer requires a unified application server version The 3x version of websocketservlet is implemented instead of the @ serverendpoint annotation endpoint of jsr356. For websocket clients, Mainstream browsers (including PC and mobile terminals) now support the standard HTML5 websocket API, which means that the websocket javascirpt script on the client has good consistency and cross platform characteristics. The following lists the support of common browser manufacturers for WebSockets: Manufacturer's application server notes: the client websocket API has basically been used in various mainstream browser factories Therefore, the JavaScript API of websocket client defined in standard HTML5 can be used. Of course, the open-source framework that meets the websocket Standard Specification in the industry can also be used, such as socket io。 The following is a code example to illustrate the client implementation of websocket: the first line of code is to apply for a websocket object, and the parameter is the address of the server to be connected. Like the beginning of HTTP protocol, the URL of websocket protocol starts with WS: / / and the secure websocket protocol starts with WSS: / /. From line 2 to line 5, the websocket object registers the message processing function. The websocket object supports four messages: onopen, onmessage, onclose and onerror. With these four events, we can easily control websocket. When browser and websocke

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>