Tuesday, 10 September 2013

Long polling in 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 . 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.

No comments:

Post a Comment