Search code examples
javasocketslong-pollingpolling

long polling using java-sockets


I have developed a java based-client that makes a connection to a server using Java-sockets. For information-exchange I used http-Protocol. Basically, I make a connection via a socket and I wrote a method on client side that makes http-requests to the server. The Server, to which I am connecting is a very simple server that I developed by my self.I want to ask, whether it is possible to make a long polling using request-method via sockets.

Since I have a request-method in my class client, I have two Options: a continuous request: consists in sending each millisecond a request asking, whether a new event occured. A prolonged request (called long polling): client send a request. The Server will answer, if it has the response. Otherwise it will not send a response and the request will time out. At that time the client send a new request

Here is a description of my model:

I wrote a simple http-client and a simple http-server. 
*The client has a method request 
* the server has a method respond.
*The client send a get-request by using its request-method to my server (gives back a command to the client)
**That server reponds to this request using its respond-method.  

How can I extend my program? How can I implement a long polling using my available client and server?


Solution

  • I would say for a simple solution (performance and such left aside) you don't need to do much: You are requesting an "event" from the server. The server accepts requests in a loop and delegates the handling of each request to a different thread (see java.util.concurrent.ExecutorService). Each handling thread waits until an event is available (you could use java.util.concurrent.BlockingQueue) and responds the request. If there is a timeout configured (see Socket.setSoTimeout, it is possible to have no timeout at all) and the timeout elapses (throwing java.net.SocketTimeoutException), the client can close the existing connection and connect again.

    For stability reasons I would set some (long) timeout, because otherwise a broken connection might not be recognized.

    If you have many clients, consider using non-blocking IO on the server. With a traditional ServerSocket each client will block a thread. If this is not an issue, stick to ServerSocket as it is less complicated and more intuitive.

    If you don't want to reinvent the wheel, have a look at Jetty or similar libraries for the HTTP part. You can still have the same structure, but instead of a plain binary stream you get a nice HttpRequest.