Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the ordinary polling Ajax method

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "how to achieve general polling Ajax". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Long connection, long polling (long polling) of Web communication

Long connection based on HTTP is a technology to realize "server push" through long polling. It makes up for the deficiency of HTTP's simple request and response mode, and greatly enhances the real-time and interaction of the program.

1. What is long connection and long polling?

In easy-to-understand terms, the client keeps sending requests to the server to get the latest data information. The "non-stop" here actually stops, but our eyes can't tell whether it stops or not, it's just a quick stop and then starts to connect immediately.

Second, the application scenarios of long connection and long polling

Long connection and long polling are generally used in WebIM, ChatRoom and some website applications that require timely interaction. Its real cases are: webQQ, Hi web version, Facebook IM and so on.

Third, advantages and disadvantages

Polling: the client sends an Ajax request to the server regularly, and the server returns the response information and closes the connection immediately after receiving the request.

Pros: it is easy to write back-end programs.

Disadvantages: most of the requests are useless, wasting bandwidth and server resources.

Example: suitable for small applications.

Long polling: the client sends an Ajax request to the server. After receiving the request, the server hold stops the connection, returns the response information and closes the connection until there is a new message, and the client sends a new request to the server after processing the response information.

Advantages: there are no frequent requests in the case of no message, and the cost of resources is small.

Disadvantages: server hold connections will consume resources, the order of returned data is not guaranteed, and it is difficult to manage and maintain.

Examples: webQQ, Hi web version, Facebook IM.

Persistent connection: embed a hidden iframe in the page and set the src property of the hidden iframe to either a persistent connection request or a xhr request, so that the server can continuously input data to the client.

Advantages: messages arrive in real time, no useless requests are sent, and it is relatively convenient to manage.

Cons: maintaining a long connection on the server increases overhead.

Example: Gmail chat

Flash Socket: embed a Flash program JavaScript that uses the Socket class in the page to communicate with the Socket interface of the server by calling the Socket interface provided by the Flash program. JavaScript controls the display of the page after receiving the information sent by the server.

Pros: achieve real instant messaging, not pseudo-instant messaging.

Disadvantages: the client must install the Flash plug-in; non-HTTP protocol, can not automatically pass through the firewall.

Example: online interactive games.

Fourth, the realization principle

The so-called persistent connection is to create and maintain a stable and reliable connection between the client and the server. In fact, it is a kind of technology that existed for a long time, but due to the slow development of browser technology, it does not provide good support for the implementation of this mechanism. Therefore, in order to achieve this effect, the programs of the client and the server need to work together. The usual practice is to add an endless loop to the server's program to monitor changes in the data in the loop. When new data is found, it is immediately output to the browser and disconnected. After receiving the data, the browser initiates a request again to enter the next cycle, which is often called long polling (long-polling).

1. Establishment of polling

The process of establishing polling is very simple. After the browser initiates the request, the browser enters a loop waiting state. At this time, because the server has not replied, HTTP has been in the connected state.

two。 Push of data

In the process of the cycle, the server program monitors the data changes, if it finds updates, outputs the information to the browser, then disconnects, completes the response process, and realizes "server push".

3. Termination of polling

Polling may be terminated in the following three situations:

3.1. There is a new data push

When the server pushes information to the browser during the loop, it should actively end the program and disconnect the connection, so that the browser can receive the data in time.

3.2. No new data push

The cycle cannot last forever, so a maximum time limit should be set to avoid WEB server timeout (Timeout). If there is no new information, the server should take the initiative to send a normal response to this poll with no new information to the browser and disconnect, which is also known as "heartbeat" information.

3.3. Network failure or exception

A request timeout or error caused by factors such as a network failure may also cause an unexpected interruption of polling, when the browser will receive an error message.

4. Reconstruction of polling

After receiving the reply and processing it accordingly, the browser should immediately re-initiate the request and start a new polling cycle.

5. Program design

1. General polling Ajax method

Client code snippet

$(function () {)

Window.setInterval (function () {

Get ("${pageContext.request.contextPath} / communication/user/ajax.mvc", {"timed": new Date () .getTime ()}, function (data) {$("# logs") .append ("[data:" + data + "]");}, 3000)

});

What the client implements is the result of an ordinary poll, which is relatively simple. Using the continuous refresh of setInterval to get the resources of the server, the advantage of this way is simple and timely. The disadvantage is that most of the links are invalid and duplicated; the results of the response are out of order (because it is an asynchronous request, when the sent request does not return a result, the subsequent request is sent. At this time, if the latter request returns the result earlier than the previous request, then when the previous request returns the result data, it is already outdated and invalid data); there are many requests, which is difficult to maintain and waste server and network resources.

Server-side code

@ RequestMapping ("/ ajax") public void ajax (long timed, HttpServletResponse response) throws Exception {PrintWriter writer = response.getWriter ()

Random rand = new Random (); / / query whether there are data changes in the endless loop while (true) {Thread.sleep (300); / / dormant for 300ms, simulate business processing, etc. Int I = rand.nextInt / / generate a random number if (I > 20 & & I < 56) {/ / if the random number is between 20 and 56, it is regarded as valid data, and the simulated data changes long responseTime = System.currentTimeMillis () / / return data information, request time, return data time, time-consuming writer.print ("result:" + I + ", response time:" + responseTime + ", request time:" + timed + ", use time:" + (responseTime-timed)); break; / / jump out of the loop, return data} else {/ / simulate no data change, sleep hold and connect Thread.sleep (1300);}}

}

Server-side implementation, here on the simulation of the program monitoring data changes. The above code belongs to a method in controller in SpringMVC, which is equivalent to a doPost/doGet method in Servlet. If there is no program environment to adapt to servlet, just copy the code in the method body to the doGet/doPost of servlet.

The server side should pay attention to the following points when programming for a long connection:

1. The controllability of server programs to polling

Because polling is implemented in an endless loop, the algorithm should ensure that the program has complete control over when to exit the loop to avoid entering the dead loop and exhausting server resources.

two。 Reasonable selection of "heartbeat" frequency

As can be seen from figure 1, persistent connections must be maintained by constant requests from the client, so it is critical to maintain a normal "heartbeat" between the client and the server. The parameter POLLING_LIFE should be less than the timeout of the WEB server, which is generally recommended to be about 10 to 20 seconds.

3. The influence of network factors

In practical application, there is a time delay from the response of the server to the establishment of the next cycle, and the delay time is affected by many factors such as network transmission. during this period, the long connection is in the gap of temporary disconnection. if any data happens to change during this period of time, the server cannot push immediately, so In the algorithm design, we should pay attention to solve the problem of data loss caused by delay.

4. Server performance

In persistent connection applications, the server maintains a persistent connection with each client instance, which consumes a lot of server resources, especially in some large application systems. a large number of concurrent persistent connections may lead to new requests being blocked or even system crash. therefore, special attention should be paid to the optimization and improvement of algorithms when programming. If necessary, you also need to consider server load balancing and clustering technology.

The above figure shows the returned result. You can see that the request is issued first, and the result may not be returned first. This does not guarantee the order, resulting in dirty data or useless connection requests. It can be seen that the resources of the server or network are wasted.

2. General polling iframe mode

$(function () {)

Window.setInterval (function () {$("# logs") .append ("[data:" + $($("# frame"). Get (0) .contentDocument). Find ("body"). Text () + "]"); $("# frame") .attr ("src", "${pageContext.request.contextPath} / communication/user/ajax.mvc?timed=" + new Date (). GetTime ()) / / delay 1 second and then request window.setTimeout again (function () {window.frames ["polling"] .location.reload ();}, 1000);}, 5000)

});

The client program here is to use the hidden iframe to constantly pull data from the server and fill the page with the data obtained by iframe. Like the fundamentals of the ajax implementation, the only difference is that when one request does not respond to return data, the next request will start, and the previous request will be stopped. If you want the program to do the same as the ajax request above, you can assign a separate iframe to each request. The following is the result returned:

Where red is the request that is stopped without a successful return request (the later request starts), and black is the request that successfully returns data.

3. Iframe mode of long connection

$(function () {)

Window.setInterval (function () {var url = "${pageContext.request.contextPath} / communication/user/ajax.mvc?timed=" + new Date () .getTime (); var $iframe = $(''); $("body") .append ($iframe)

$iframe.load (function () {$("# logs") .append ("[data:" + $($iframe.get (0) .contentDocument) .find ("body"). Text () + "]); $iframe.remove ();});}, 5000)

});

This polling method is to change the above slightly. Each request has its own independent iframe. When the iframe gets the response data, it will push the data to the current page. Using this method is already similar to the asynchronous interaction of ajax, this method can not guarantee the order, is more resource-consuming, and there is always a loaded bar in the address bar or status bar attachment (of course, the siege masters who can make use of htmlfile,Google have already done it, and there is also an encapsulated lib library on the Internet), but the client side is relatively simple to implement.

If you want to be orderly, instead of using setInterval, you can put the method that creates the iframe in the load event, even if recursively. The adjusted code snippet is as follows:

$(function () {(function iframePolling () {var url = "${pageContext.request.contextPath} / communication/user/ajax.mvc?timed=" + new Date () .getTime (); var $iframe = $(''); $("body") .append ($iframe)

$iframe.load (function () {$("# logs") .append ("[data:" + $($iframe.get (0) .contentDocument) .find ("body") .text () + "]); $iframe.remove ()

/ / Recursive iframePolling ();});}) ();})

Although this approach ensures the order of requests, it does not handle request delay errors or requests that have not returned a result for a long time. It waits until the request is returned before creating the next iframe request, always maintaining a connection with the server. Compared with the above polling, the disadvantage is that the message is not timely, but ensures the order of the request.

4. Ajax implements long connection.

$(function () {)

(function longPolling () {

Ajax ({url: "${pageContext.request.contextPath} / communication/user/ajax.mvc", data: {"timed": new Date (). GetTime ()}, dataType: "text", timeout: 5000 state error: function (XMLHttpRequest, textStatus, errorThrown) {$("# state"). Append ("[state:" + textStatus + ", error:" + errorThrown + "]"); if (textStatus = "timeout") {/ / request timeout longPolling (); / / Recursive call timeout longPolling ()

/ / other errors, such as network errors} else {longPolling ();}}, success: function (data, textStatus) {$("# state") .append ("[state:" + textStatus + ", data: {" + data + "}]")

If (textStatus = = "success") {/ / request succeeded longPolling ();});}) ()

});

The above code is the Ajax way to complete a long connection, the main advantage is to maintain a connection with the server at all times. If the current connection request is successful, the data is updated and a new connection continues to be created to keep in touch with the server. If the connection times out or an exception occurs, the program will also create a new connection to continue the request. In this way, the server and network resources are greatly saved, the performance of the program is improved, and the sequence of the program is ensured.

This is the end of the content of "how to implement ordinary polling Ajax". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report