【问题标题】:Keep connection open and read data till it is forcefully closed保持连接打开并读取数据,直到它被强制关闭
【发布时间】:2014-10-16 16:22:27
【问题描述】:

当我的活动加载时,我正在连接到网络服务。当我得到服务的响应时,我再次调用服务等等。

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

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

这就是我连接服务的方式

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, '"');
        }  

是否有可能我在开始时只连接到服务一次,然后连接保持打开状态,应用程序继续从服务读取数据,直到连接被强制关闭。
如果需要更多代码,请告诉我。

更新:然后我尝试使用 ClientConnectionManager,但连接仍然一次又一次地初始化。虽然它正在获取数据。我想要的是连接保持打开状态,并继续从服务中读取数据。

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) {
         ….  
         }

【问题讨论】:

  • 连接也应该提供无限和持续的响应
  • 您的意思是响应本身会一次又一次地出现?
  • 使用 startForeground() 在前台而不是后台启动你的服务,告诉 Android 你知道它并想自己处理它。 stackoverflow.com/questions/3856767/…
  • 所以你正在寻找一个简单的 HttpClient 请求上的类似套接字的连接?不会按您预期的方式工作。
  • 你需要一个 Socket... 查看@Justin Powell 的回答!

标签: android httprequest


【解决方案1】:

听起来您真正需要的是套接字连接(请参阅here)。套接字将保持连接,并允许您与套接字服务器来回传输数据,直到完成。

【讨论】:

    【解决方案2】:

    您只需要在完成使用/阅读后关闭从HttpResponse.getEntity().getContent() 获得的InputStream。这将正式表明您当前请求的结束。

    然后您可以继续执行另一个请求,将使用相同的 HttpClient 连接。

    添加关闭

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

    【讨论】:

      【解决方案3】:

      我是否可以在开始时只连接一次服务, 然后连接保持打开...

      网络服务器在这方面可以发挥作用。如果服务器“结束” HTTP 响应,在同一个 HTTP 调用上将不会发生进一步的通信。

      可以在服务器的帮助下保持 HTTP 连接打开。在这种情况下,服务器永远不会真正结束响应,而是在一段时间后继续向响应流写入数据,因此客户端可以继续监听。

      上述技术的新替代品是双工套接字连接。客户端和服务器都可以通过套接字发送和接收消息。同样,客户端和服务器都必须正确支持它,并且必须对连接丢失等进行必要的处理。

      有一些 android 特定的客户端实现可用,例如 https://github.com/nkzawa/socket.io-client.java,它们会为您处理大部分连接管理。

      【讨论】:

        【解决方案4】:

        我认为您可以尝试使用 AsyncTask 类来尝试保持线程打开并做您想做的事情,如下所示:

        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() { ... }
        }
        

        查看the API documentation了解更多信息;)

        【讨论】:

          猜你喜欢
          • 2012-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-10
          • 1970-01-01
          相关资源
          最近更新 更多