简体   繁体   English

在JQuery + JAVA中长时间轮询?

[英]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 . 我需要在服务器中 保留我的请求,直到新数据出现。我使用Tomcat 6作为我的Web服务器。 So this is my JQuery code, 所以这是我的JQuery代码,

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 , 我的java代码将是,

@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 . 但是每隔11秒就会有一个continous request sent to server I don't know how it is possible. 我不知道怎么可能。 I have checked this with chrome developer tools . 我用chrome开发人员工具检查过这个。

在此输入图像描述

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: 根据您的浏览器和(特别是)前端服务器(Apache / NGINX)和Web服务器(Tomcat?)配置,您将拥有:

  • maximum wait time for the first response (connection timeout, probably 10 seconds in your case) 第一个响应的最长等待时间(连接超时,在您的情况下可能是10秒)
  • 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 如果(超时)错误,请转到步骤1

Please note that this solution is not scalable: usually you would have (for example) 200 thread processing incoming requests. 请注意,此解决方案不可扩展:通常您将(例如)200个线程处理传入请求。 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. 但是使用200个线程,您可以为超过2.000个用户提供服务。 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. 如果可能的话,你应该真正研究WebSockets ,它现在可以在新版本的Java中使用。

EDIT As Konrad suggested below, you can use something like socket.io , which falls-back automatically to other mechanisms. 编辑正如Konrad在下面建议的那样,你可以使用类似socket.io的东西,它可以自动回退到其他机制。 There's a Java-based implementation for sever-side available call Atmosphere , but I haven't tried it though. 有一个基于Java的实现服务器端可用呼叫Atmosphere ,但我还没有尝试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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