I am trying to create a multi user chat environment using the base example from https://github.com/rstoyanchev/spring-mvc-chat
I am not able to find what exactly is wrong with my code. The request is not polling it just keeps on firing request continuously to the server.
Following are my code snipets
web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
applicationContext.xml
<mvc:annotation-driven>
<mvc:async-support default-timeout="30000" />
<mvc:message-converters register-defaults="false">
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
Controller
@Controller
@RequestMapping("/chat")
public class ChatController
{
@RequestMapping("messages")
@ResponseBody
public DeferredResult<List<String>> getMessages()
{
final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(30000l, Collections.emptyList());
this.chatRequests.put(deferredResult, 0);
deferredResult.onCompletion(new Runnable()
{
@Override
public void run()
{
chatRequests.remove(deferredResult);
}
});
List<String> messages = new ArrayList<String>();
messages.add("first");
if (!messages.isEmpty())
{
deferredResult.setResult(messages);
}
return deferredResult;
}
}
javascript
function chatModel(){
var started = false;
var that = this;
that.activePollingXhr = ko.observable(null);
function pollForMessages() {
that.activePollingXhr($.ajax({
url : contextPath + '/chat/messages',
type : "GET",
cache : false,
success : function(messages) {
console.log(messages);
},
error : function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
console.log('Unable to Connect');
}
},
complete : pollForMessages
}));
}
Got the issue. if we set results
deferredResult.setResult();
it dont wait so goes into recursive calling.