简体   繁体   中英

Long polling in JQuery + JAVA?

I need to hold my request in the server until new data comes.I am using the Tomcat 6 as my web server . So this is my JQuery code,

function sendMessage() {

    var message = $("#message").val();
    $.ajax({
        type: "POST",
        cache: false,
        url: "sendMessage.html",
        data: "message=" + message,
        dataType: "html",

        success: function(response) {

        },
        error: function(e) {
            //alert('Error: ' + e);
        },
    });
}


function startLongPolling(){

    $.ajax({
        type: "POST",
        cache: false,
        url: "LongPoll.html",
        dataType: "html",
        success: function(response) {   
            if(response != null && response !="" && response !="null")
                $("#sucess").html(response);
        },
        error: function(e) {
            //alert('Error: ' + e);
        },

        complete: function(e) {
            startLongPolling();
        },
    });
}

My java code will be ,

@RequestMapping(value = "LongPoll.html", method=RequestMethod.POST )
public @ResponseBody String longLongPolling(HttpSession session) {

    String sessionId = session.getId().toString();
    AgentState agentState = ApplicaionManager.agentDetail.get(sessionId);
    String message = null;

    if(ApplicaionManager.agentDetail.containsKey(sessionId)){

        while(true){

            if(agentState.isStateChange() == true){
                message = agentState.getMessage();
                if(message != null)
                    agentState.setStateChange(false);
                System.out.println("Break for session "+sessionId+" due to Agent State changed");
                break;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("While exited for session"+sessionId);
    return message;
}

But there is a continous request sent to server for every 11 seconds . I don't know how it is possible. I have checked this with chrome developer tools .

在此输入图像描述

Hope our stack users will help me.

This is normal / expected. Depending on your browser and (especially) front-end server (Apache/NGINX) and web-server (Tomcat?) configuration you will have:

  • maximum wait time for the first response (connection timeout, probably 10 seconds in your case)
  • maximum wait time for the complete response

These setting basically prevent the server from being spammed with requests that never complete and running out of threads in the thread pool.

You could increase these values, however you should always create your code like this with timeouts in mind. Basically you want to do on the client side:

  • Open long pull
  • Wait for response
  • If received, continue
  • If (timeout) error, go to step 1

Please note that this solution is not scalable: usually you would have (for example) 200 thread processing incoming requests. The idea is that they finish fast. If the thread pool is exhausted, users will have to wait for a new connection. But with 200 threads you are able to serve well over 2.000 users. But not if threads are blocked because of long pool.

If possible, you should really look into WebSockets , which are now available in new versions of Java.

EDIT As Konrad suggested below, you can use something like socket.io , which falls-back automatically to other mechanisms. There's a Java-based implementation for sever-side available call Atmosphere , but I haven't tried it though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM