Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring longpolling example code?

I can find lots of information on how Long Polling works (For example, this, and this), but no simple examples of how to implement this in code.

Basically, how would I use Apache Tomcat to serve the requests, and how would I write a simple app ( spring ) which would "long-poll" the server for new messages?

The example doesn't have to be scaleable, secure or complete, it just needs to work! I would appreciate it if anyone could give me such a tutorial or refer any other.

like image 874
Bhaskar Avatar asked Oct 22 '22 13:10

Bhaskar


1 Answers

Here is the simplest example I can come up with...

In the controller:

@RequestMapping("/longPolling")
public String longPolling(Model model) {
  while(true) {
    // .. Do something, break when done...
    if( somethingIsDone ) {
       break;
    }
  }
  return "someResponse";
}

In the View calling this, you would setup an ajax call, and on a timeout simply call this again. The idea of long polling is that the server just doesn't respond until it has something to respond with.

A better approach, if you are using Spring 3.2, is to use DeferredResult or return a Callable from your handler method. If you are pre-Spring 3.2, then there are several frameworks you can use to help, like Atmosphere, that work just fine with Spring. Some even have JavaScript parts to ease the client-side coding.

like image 157
CodeChimp Avatar answered Oct 27 '22 23:10

CodeChimp