Skip to content Skip to sidebar Skip to footer

Keep Connection Open And Read Data Till It Is Forcefully Closed

When my activity loads, I am connecting to a web service. As and when I get the response from service, I again call then service and so on. @Override protected void onCreate(Bund

Solution 1:

It sounds like what you really need is a socket connection (see here). A socket will stay connected and allow you to stream data back and forth with the socket server until you are finished.

Solution 2:

you just need to close the InputStream you get from HttpResponse.getEntity().getContent() after you are done using/reading-it. This will officially indicate the end of your current request.

You can then proceed to execute another request, the same HttpClient connection will be used.

Add a close

        InputStream instream = entity.getContent();
        response = convertStreamToString(instream); 
        // close the InputSream
        instream.close()

        // you can now reuse the same `HttpClient` and execute another request// using same connection
        httpResponse = client.execute(request);

Solution 3:

Is it possible that I connect to the service only once at the start, then the connection remains open...

The web server has a role to play in this. If the server "ends" the HTTP response, there is no further communication going to happen on same HTTP call.

It is possible to keep an HTTP connection open, with help of server. In this case, server never really ends the response but keeps writing data to response stream after some time intervals, so client can keep listening.

The new replacement for the above technique is a duplex socket connection. Both client and server can send and receive messages over a socket. Again, both client and server have to support it properly, and necessary handling for connection drops etc has to be there.

There are android specific client implementations available like https://github.com/nkzawa/socket.io-client.java that take care of most of connection management for you.

Solution 4:

I think you could try to use the AsyncTask class to try to keep your thread open and do what you want, like this:

publicclassConnectToWebServiceextendsAsyncTask<Void, Void, Boolean> {

    @OverrideprotectedBooleandoInBackground(Void... params) { ... }

    @OverrideprotectedvoidonPostExecute(final Boolean success) { ... }

    @OverrideprotectedvoidonCancelled() { ... }
}

Check the API documentation for more information ;)

Post a Comment for "Keep Connection Open And Read Data Till It Is Forcefully Closed"