Keep the connection open and read data until it is forcibly closed

When my activity loads, I connect to the web service. When and when I receive a response from the service, I call the service again and so on.

@Override
protected void onCreate(Bundle savedInstanceState) {  
….  
callWebMethod();
}  

// Called on getting response  
@Override
public void run(String value) {  
….  
callWebMethod();  
}  

      

This is how I connect to the service

HttpGet request = new HttpGet(url + combinedParams);  
HttpClient client = new DefaultHttpClient(httpParameters);

    HttpResponse httpResponse;

        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);
            response = StringUtils.remove(response, "\n");
            response = StringUtils.remove(response, '"');
        }  

      

Is it possible that I only connect to the service once at the beginning, then the connection remains open and the application continues to read data from the service until the connection is forcibly closed.
Please let me know if more code is required.

Refresh . Then I tried with ClientConnectionManager, but still the connection is initialized over and over again. Although he is receiving data. I want the connection to remain open and continue to read data from the service.

HttpParams httpParameters = new BasicHttpParams ();

    SharedPreferences preferences = context.getSharedPreferences(
            "MyPreferences", Context.MODE_PRIVATE);

    int timeoutConnection = Integer.parseInt(preferences.getString(
            "timeout", "60")) * 1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);

    HttpConnectionParams.setSoTimeout(httpParameters, 2000);
    System.setProperty("http.keepAlive", "true");
    HttpClient client = new DefaultHttpClient(httpParameters);

    ClientConnectionManager mgr = client.getConnectionManager();
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(
            client.getParams(), mgr.getSchemeRegistry()),
            client.getParams());
    while (true) {

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                response = StringUtils.remove(response, "\n");
                response = StringUtils.remove(response, '"');
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        callback.run(response);  // This calls activity callback function.
                    }
                });

                // Closing the input stream will trigger connection release
                // instream.close();
            }

        } catch (ConnectTimeoutException e) {
         ….  
         }

      

+3


source to share


4 answers


It looks like you really need socket connections (see here ). The socket will remain connected and will allow you to send data back and forth with the socket server until you are done.



+12


source


you just need to close InputStream

which you get from HttpResponse.getEntity().getContent()

after you finish using / read -it. This will officially indicate the end of your current request.

Then you can make another request, the same HttpClient connection will be used.



Add closure

        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);

      

+2


source


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

The web server must play a role in this. If the server "completes" the HTTP response, no further communication will take place on the same HTTP call.

You can open an HTTP connection using a server. In this case, the server never finishes the response, but continues to write data to the response stream at regular intervals, so the client can keep listening.

A new replacement for the above method is a duplex socket connection. The client and server can send and receive messages over the socket. Again, both the client and the server need to support it properly, and the necessary processing to reset the connection, etc. Should be there.

There are special versions of Android apps like https://github.com/nkzawa/socket.io-client.java that take care of most of the connection management for you.

+2


source


I think you could try using a class AsyncTask

to try and keep your stream open and do what you want, like this:

public class ConnectToWebService extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) { ... }

    @Override
    protected void onPostExecute(final Boolean success) { ... }

    @Override
    protected void onCancelled() { ... }
}

      

Read more on the API documentation for more information;)

+2


source







All Articles