Long polling, long polling for WEB communication

Source: Internet
Author: User

Long-time connection based on HTTP is a technology of "server push" through long polling, which makes up the insufficiency of HTTP simple request answering mode, and greatly enhances the real and interactive of the program.

First, what is long connection, long polling?

In plain terms, the client is constantly sending requests to the server to get the latest data. The "Stop" here actually has a stop, but our human eyes can not tell whether or not to stop, it is just a quick stop and then immediately began to connect.

Second, long-connected, long-polling application scenarios

Long connections, long polling general applications with Webim, chatroom and some Web applications that need to interact in a timely manner. Its real cases are: WEBQQ, HI Web version, Facebook im and so on.

If you are interested in server-side reverse Ajax, you can refer to this article DWR reverse AJAX server-side push way: http://www.cnblogs.com/hoojo/category/276235.html

You are welcome to continue to support and follow my blog:

Http://hoojo.cnblogs.com

Http://blog.csdn.net/IBM_hoojo

You are also welcome to communicate with me and explore the knowledge of it.

Email:[email protected]

Iii. Advantages and Disadvantages

Polling: The client periodically sends an AJAX request to the server, returning the response information and closing the connection as soon as the server receives the request.
Pros: It's easier to write back-end programs.
Cons: Half 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, the server receives the request and hold the connection until a new message returns the response information and closes the connection, and the client finishes processing the response and sends a new request to the server.
Advantages: In the absence of a message without frequent requests, the cost of small resources.
Cons: Server hold connections consume resources, return data order is not guaranteed, difficult to manage maintenance.
Example: WEBQQ, HI Web version, Facebook IM.

Long connection: embed a hidden iframe in the page, set the SRC attribute of the hidden IFRAME to a request for a long connection, or use a XHR request, and the server can continuously enter data to the client.
Advantage: The message arrives immediately, does not send the useless request, the management is also relatively convenient.
Disadvantage: The server maintains a long connection that increases overhead.
Example: Gmail Chat


Flash Socket: embed a flash program JavaScript using the socket class within the page to communicate with the server-side socket interface by invoking the socket interface provided by this flash program. JavaScript controls the display of the page after it receives information from the server side.
Pros: Realize real instant communication, not pseudo-instant.
Disadvantage: The client must have a Flash plugin installed, a non-HTTP protocol, and cannot automatically traverse the firewall.
Example: Network interactive game.

Iv. Principle of realization

The so-called long connection is to create and maintain a stable and reliable connection between the client and the server. In fact, it is a very early existence of technology, but because of the development of browser technology is relatively slow, not for the implementation of this mechanism to provide a good support. So to achieve this effect, the client and server programs need to work together to complete. It is common practice to include a dead loop in the server's program to monitor the data changes in the loop. When new data is found, it is immediately output to the browser and disconnected, the browser after receiving the data, the request again to enter the next cycle, this is often said long polling (long-polling) way. As shown, it usually contains the following key processes:

1. The establishment of polling
The polling process is simple, the browser initiates the request to enter the loop wait state, at this time because the server has not responded, so HTTP has been in the connected state.
2. Data push
During the cycle, the server program monitors data changes, such as discovering updates, outputting the information to the browser, disconnecting it, completing the answer process, and implementing a "server Push".
3. Termination of polling
Polling may be terminated in the following 3 scenarios:
3.1. New data push
When the server pushes information to the browser during the loop, it should actively end the program and let the connection disconnect so that the browser can receive the data in a timely manner.
3.2. No new data push
The cycle can not continue, should be set a maximum time limit, to avoid the Web server timeout (timeout), if there is no new information, the server should actively send the browser this poll no new information of the normal response, and disconnect, which is also known as the "Heartbeat" information.
3.3. Network failure or exception
The browser will receive an error message when a request time-out or an error caused by a network failure can cause an unexpected interruption in polling.
4. Polling for reconstruction
Once the browser receives the reply and processes it, it should restart the request immediately and start a new polling cycle.

V. Programming

1, ordinary polling Ajax way

Client Code Snippets

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8" iselignored= "false"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  
    
        <meta http-equiv= "Pragma" content= "No-cache" >
        <meta http-equiv= "Cache-control" content= "No-cache" >
        <meta http-equiv= "Author" content= "Hoojo & http://hoojo.cnblogs.com" >
        <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
        <%@ include file= "/tags/jquery-lib.jsp"%>
        
        <script type= "Text/javascript" >
            $ (function () {
            
                Window.setinterval (function () {
                
                    
                        
                        function (data) {
                            $ ("#logs"). Append ("[Data:" + Data + "]<br/>");
                    });
                }, 3000);
                
            });
        </script>
    
    
    <body>
        <div id= "Logs" ></div>
    </body>

  

The client implements the result of using a common poll, which is relatively simple. The advantage of using setinterval uninterrupted refresh to get the resources of the server is simple and timely. The disadvantage is that the links are mostly invalid duplicates; The result of the response is not sequential (because it is an asynchronous request, and the subsequent request is sent when the request is sent without returning the result.) At this point, if the subsequent request is more than the previous request to return results, then when the previous request returned result data is already obsolete invalid data, the request is more difficult to maintain, 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 ();
     Dead loop query with no data changes
     while (true) {
         Thread.Sleep (300); Sleeps 300 milliseconds, simulates processing business, etc.
         int i = rand.nextint (100); Generate a random number between 0-100
         if (i > && i < 56) {//If the random number is treated as valid data between 20-56, the analog data is changed
             Long responsetime = System.currenttimemillis ();
             Returns data information, request time, return data time,
             Writer.print ("Result:" + i + ", Response time:" + ResponseTime + ", Request time:" + timed + ", use time:" + (response time-timed));
             Break Jump out of the loop, return data
         } else {//simulate no data changes, put sleep hold connection
             Thread.Sleep (1300);
         }
     }
     
}

Server-side implementation, here to simulate the changes in the program monitoring data. The above code belongs to a method in the controller in Springmvc, which is equivalent to a Dopost/doget method in the servlet. If no program environment adapts to the servlet, copy the code from the method body into the doget/dopost of the servlet.

The server side in the long-connection programming, should pay attention to the following points:
1. The controllability of the server program to
polling
Since polling is implemented in the form of a dead loop, it is necessary to ensure that the program has complete control over when to exit the loop, and avoids running out of server resources in a dead loop.
2. Select the "Heartbeat" frequency reasonably
As can be seen from Figure 1, the long connection must be maintained by the client constantly request, so the client and the server to maintain a normal "heartbeat" to be critical, the parameter polling_life should be less than the Web server time-out, generally recommended in about 10-20 seconds.
3. Impact of network factors
In the actual application, from the server to answer, to the establishment of the next cycle, there is a time delay, the length of the delay is affected by a variety of factors such as network transmission, in this period of time, the long connection is temporarily disconnected in the empty file, if there is data in this period of time changes, the server can not immediately push, so, The problem of data loss due to delay may be addressed in the design of the algorithm.
4. Performance of the server
In a long-connected application, the server maintains a persistent connection to each client instance, which consumes a lot of server resources, especially in some large applications, where a large number of concurrent long connections can cause new requests to be blocked or even crash, so In the process of programming, special attention should be paid to the optimization and improvement of the algorithm, as well as server load balancing and cluster technology when necessary.

Is the result of the return, you can see that the request was made first, not necessarily the result first. This does not guarantee the order, resulting in dirty data or useless connection requests. Visible waste of resources on the server or network.

2, ordinary polling iframe mode

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8" iselignored= "false"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  
    
        <meta http-equiv= "Pragma" content= "No-cache" >
        <meta http-equiv= "Cache-control" content= "No-cache" >
        <meta http-equiv= "Expires" content= "0" >
        <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
        <%@ include file= "/tags/jquery-lib.jsp"%>
        
        <script type= "Text/javascript" >
            $ (function () {
            
                Window.setinterval (function () {
                    $ ("#logs"). Append ("[Data:" + $ ($ ("#frame"). Get (0). contentdocument). Find ("Body"). Text () + "]<br/>");
                    $ ("#frame"). attr ("src", "${pagecontext.request.contextpath}/communication/user/ajax.mvc?timed=" + New Date (). GetTime ());
                    Delay 1 seconds and re-request
                    Window.settimeout (function () {
                        window.frames["Polling"].location.reload ();
                    }, 1000);
                }, 5000);
                
            });
        </script>
    
    
    <body>
        <iframe id= "Frame" name= "polling" style= "Display:none;" ></iframe>
        <div id= "Logs" ></div>
    </body>

  

The client program here is to use the hidden iframe to the server end of the pull data, the IFRAME gets the data to populate the page. Just like the basic principle of AJAX implementations, the only difference is that when a request does not respond to the 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, assign a separate iframe to each request. The following is the result of the return:

Where red is a request that is stopped (after a request) without a successful return request, Black is the request to successfully return the data.

3. Long connected IFRAME mode

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8" iselignored= "false"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  
    
        <meta http-equiv= "Pragma" content= "No-cache" >
        <meta http-equiv= "Cache-control" content= "No-cache" >
        <meta http-equiv= "Author" content= "Hoojo & http://hoojo.cnblogs.com" >
        <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
        <%@ include file= "/tags/jquery-lib.jsp"%>
        
        <script type= "Text/javascript" >
            $ (function () {
            
                Window.setinterval (function () {
                    var url = "${pagecontext.request.contextpath}/communication/user/ajax.mvc?timed=" + New Date (). GetTime ();
                    var $iframe = $ (' <iframe id= "frame" name= "polling" style= "Display:none;" src= "' + URL + ' ></iframe> ');
                    $ ("Body"). Append ($iframe);
                
                    $iframe. Load (function () {
                        $ ("#logs"). Append ("[Data:" + $ ($iframe. Get (0). contentdocument). Find ("Body"). Text () + "]<br/>");
                        $iframe. Remove ();
                    });
                }, 5000);
                
            });
        </script>
    
    
    <body>
        
        <div id= "Logs" ></div>
    </body>

  

This polling method is to change the above slightly, each request has its own independent IFrame, when the IFRAME gets the response data, push the data to the current page. Using this method has been similar to the asynchronous interaction of Ajax, this method is not guaranteed sequential, more resource-intensive, and always have a loaded bar in the address bar or the status bar attachment (of course, to solve the htmlfile,google can take advantage of the siege division has done, There is also a well-packaged Lib library on the web, but the client is relatively simple to implement.

If you want to ensure order, you can not use SetInterval, the method of creating an IFrame in the Load event, that is, the use of recursion . The following code snippet is adjusted:

<script type= "Text/javascript" >
    $ (function () {
        (function iframepolling () {
            var url = "${pagecontext.request.contextpath}/communication/user/ajax.mvc?timed=" + New Date (). GetTime ();
            var $iframe = $ (' <iframe id= "frame" name= "polling" style= "Display:none;" src= "' + URL + ' ></iframe> ');
            $ ("Body"). Append ($iframe);
        
            $iframe. Load (function () {
                $ ("#logs"). Append ("[Data:" + $ ($iframe. Get (0). contentdocument). Find ("Body"). Text () + "]<br/>");
                $iframe. Remove ();
                
                Recursive
                Iframepolling ();
            });
        })();    
    });
</script>

This approach guarantees the order of the request, but it does not handle the request delay error or a request that has not returned a result for a long time, it waits until the request is returned to create the next IFRAME request, and always maintains a connection with the server. Compared to polling, the disadvantage is that the message is not timely, but the order of the request is guaranteed.

4. Ajax for long connections

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8" iselignored= "false"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  
    
        <meta http-equiv= "Pragma" content= "No-cache" >
        <meta http-equiv= "Cache-control" content= "No-cache" >
        <meta http-equiv= "Expires" content= "0" >
        <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
        <%@ include file= "/tags/jquery-lib.jsp"%>
        
        <script type= "Text/javascript" >
            $ (function () {
            
                (function longpolling () {
                
                    $.ajax ({
                        URL: "${pagecontext.request.contextpath}/communication/user/ajax.mvc",
                        Data: {"timed": New Date (). GetTime ()},
                        DataType: "Text",
                        timeout:5000,
                        Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
                            $ ("#state"). Append ("[State:" + textstatus + ", Error:" + Errorthrown + "]<br/>");
                            if (Textstatus = = "Timeout") {//Request timed out
                                    Longpolling (); Recursive invocation
                                
                                Other errors, such as network errors, etc.
                                
                                    Longpolling ();
                                }
                            },
                        Success:function (data, textstatus) {
                            $ ("#state"). Append ("[State:" + Textstatus + ", data: {" + Data + "}]<br/>");
                            
                            if (Textstatus = = "Success") {//Request succeeded
                                Longpolling ();
                            }
                        }
                    });
                })();
                
            });
        </script>
    
    
    <body>

The above code is the Ajax way to complete a long connection, the main advantage is to always maintain a connection with the server. If the current connection request succeeds, the data is updated and a new connection continues to be created and the server remains in contact. If the connection times out or an exception occurs, the program will also create a new connection to continue the request. This greatly saves the server and network resources, improves the performance of the program, and thus guarantees the sequence of the program.

Vi. Summary

Modern browsers support the cross-domain resource sharing (cross-origin Resource share,cors) specification, which allows XHR to perform cross-domain requests, so script-based and IFRAME-based technologies have become obsolete.

The best way to implement and use comet as a reverse Ajax is through the XMLHttpRequest object, which provides a true connection handle and error handling. Of course you choose to use the comet mode of the XMLHttpRequest object (a simple Ajax request that hangs on the server side) via HTTP long polling, and all AJAX-enabled browsers support this approach.

Long-time connection technology based on HTTP is the ideal choice for instant interactive application development in pure browser environment, HTML5 will provide better support and wider application with the rapid development of the browser. In the HTML5 there is a websocket can be very friendly to complete the long connection of the technology, the Internet also has relevant information, here also do not do too much introduction.

Long polling, long polling for WEB communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.