2013-03-12 3 views
2

Java Chat application에 대한 질문입니다.JAVA에서의 Long 폴링 Jquery?

내 외부 애플리케이션이 시작될 때 외부 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().

어떻게 LONG POLLINGJQUERY을 사용하여 얻을 수 있습니까?

스택 멤버가 도움을 주시기 바랍니다.

+0

JQUERY로만 긴 폴링을 수행 할 수있는 방법이 있습니까? –

답변

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(); 그것은 새로운 메시지가 도착할 때까지 대기 상태를 유지하기 때문에 블로킹 동작이어야한다. 또는 그 라인을 따라 무엇인가.

기본적으로 긴 폴링은 필요한 정보가 어딘가에서 검색된 다음 서버의 출력 버퍼에 기록하고 연결을 닫을 때까지 서버가 "멈춤"함을 의미합니다. 클라이언트는 다시 긴 폴링을 다시 시작하기 위해 다시 연결을 즉시 인스턴스화합니다.

+0

'JQUERY'만으로 긴 폴링을 할 수 있습니까? –

+0

그냥 정기적으로 설문 조사를하는 것이 좋습니다. 단, 일정 기간 동안 설문 조사를하지는 않지만 곧 서버에서 답장을받는 즉시 긴 설문 조사를 다시 시작하십시오. 긴 폴링은 블로킹 큐의 테이크 (take) 기능처럼 보일 것입니다. 거기에 뭔가가 있으면 얻을 수 있습니다. 그리고 당신이 평소에 무엇이든지 얻은 직후에 큐에서 가져온 것을 처리하고 take 명령을 다시 호출하십시오. 그것은 정보가있을 때까지 연결이 끊어지는 백엔드입니다. 백엔드가 아무 것도 반환하지 않을 때는 아무 것도 반환하지 않으므로 jquerry를 사용하여 그렇게 할 수 없습니다. –

+0

답장을 보내 주셔서 감사합니다. Jquery에서 long polling을 수행하는'builtin' 메소드는 무엇입니까? –