【问题标题】:Long polling Jquery in JAVA?JAVA中的长轮询Jquery?
【发布时间】:2013-02-28 02:02:17
【问题描述】:

这是我的Java Chat application 的问题。

当我的应用程序启动时,我将在我的外部 Jquery 中调用 pingAction()

Jquery pingAction 将是,

function pingAction(){

    $.ajax(
            {
                type: "post",
                url: "PingAction",
                async:     false,
                data : "userId="+encodeURIComponent(userId)+"&secureKey="+encodeURIComponent(secureKey)+"&sid="+Math.random() ,
                cache:false,
                complete: pingAction,
                timeout: 5000 ,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                scriptCharset: "utf-8" ,
                dataType: "html",

                error: function (xhr, ajaxOptions, thrownError) {
                alert("xhr.status : "+xhr.status);

                if(xhr.status == 12029 || xhr.status == 0){
                    //alert("XMLHttp status : "+xhr.status);
                    $("#serverMsg").css("backgroundColor" , "yellow");
                    $("#serverMsg").text("Your Network connection is failed !");
                    $("#serverMsg").show();
                }
                //setTimeout('pingAction()', 5000);
                xhr.abort();
            },

            success: function( responseData , status){
                if($("#serverMsg").text() == "" || $("#serverMsg").text() == "Your Network connection is failed !"){
                    disableServerMessage();
                }

                if(responseData != "null" && responseData.length != 0  && responseData != null){

                    var stringToArray = new Array;
                    stringToArray = responseData.split("<//br//>");
                    var len = stringToArray.length;
                    for(var i=0;i<len-1;i++){
                        getText(stringToArray[i]);

                    }
                }

                //setTimeout('pingAction()', 5000);
            } 

            }                           
    );

}

我的PingAction Servlet 将是,

public class PingAction extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private String secureKey;
    private String userId;
    private int fromPosition ;
    private FlexChatProtocol protocol = null;
    private Ping ping = null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("UTF-8");
        PrintWriter out = response.getWriter();

        request.setCharacterEncoding("UTF-8");

        secureKey = request.getParameter("secureKey");
        userId = request.getParameter("userId");
        CustomerInfo customer = ApplicationInfo.customerDetails.get(userId);
        if(customer != null){
            fromPosition = customer.getFromPosition();
        }

        if(ApplicationInfo.flexProtocol != null ){

            protocol = ApplicationInfo.flexProtocol;

            ping = new Ping();
            ping.sendPing(secureKey, userId, fromPosition+1, protocol, serverMessage);

            if(customer != null){
            message = customer.getFullMessage();
            }

            out.println(message);
        }
    }

}

在使用 Long Poling 之前,我将使用 setTimeInterval() 为每个 5 seconds 调用 pingAction() in javaScript 以刷新连接并获取服务器消息。

现在我需要在聊天应用程序中使用LONG POLLING concept。所以我修改了我的Jquery pinAction() 你在上面看到的内容。

如何使用JQUERY 实现LONG POLLING

希望我们的堆栈成员能帮助我!

【问题讨论】:

  • 有没有办法只用 JQUERY 进行长轮询?

标签: java jquery servlets long-polling


【解决方案1】:
private ChatContext context = ChatContext.getInstance();

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Long lastmessage = // just put this somewhere

    List<String> messages = context.getMessagesIHaventGotYet(lastmessage); // blocking call
    Object formatedMessages = formatmessages(messages);
    out.write(formatedMessages);

 }

context.getMessagesIHaventGotYet();应该是一个阻塞操作,所以它会一直等待直到新消息到达,然后它才会开始行动。 或类似的东西。

基本上长轮询意味着服务器“挂起”,直到从某个地方检索到它需要的信息,然后将其写入其输出缓冲区并关闭连接,客户端尽快再次实例化连接以开始另一个长轮询。

【讨论】:

  • 有没有办法只用JQUERY进行长轮询?
  • 就像你经常做的那样轮询,除了你不定期轮询,但是一旦你得到服务器的回复,就重新开始一个长轮询。长轮询应该被视为阻塞队列的 take 函数,如果里面有东西,你会得到它。在你得到任何东西之后,你通常只需处理你从队列中检索到的东西,然后再次调用 take 命令。它是后端使连接挂起,直到有信息,所以如果后端什么都不返回,那么你不能使用 jquery 来让它这样做......
  • 感谢您的回复。 Jquery 中的任何 builtin 方法可以执行 long polling 吗?
  • jquery 不关心与服务器的连接是短期的还是长期的。你可以只使用 $.ajax 之类的。您只需要确保连接不会超时。长轮询调用只是停留在服务器中的任何调用,直到它拥有需要响应的数据。关键是让您的服务器以非忙碌等待的方式挂起,并确保连接不会超时。
  • @G-Man 进行阻塞操作的最佳方式是什么,是一个无限循环,条件是 t 以干净的方式破坏它?
猜你喜欢
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多