保持连接打开,直到它被强制关闭读取数据 [英] Keep connection open and read data till it is forcefully closed

查看:156
本文介绍了保持连接打开,直到它被强制关闭读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动负载,我连接到​​Web服务。正如当我得到服务的响应,我再打电话,然后服务等。

  @覆盖
保护无效的onCreate(捆绑savedInstanceState){
...。
callWebMethod();
}//号召得到响应
@覆盖
公共无效的run(字符串值){
...。
callWebMethod();
}

这是我如何连接到服务

  HTTPGET请求=新HTTPGET(URL + combinedParams);
HttpClient的客户端=新DefaultHttpClient(httpParameters);    HTT presponse HTT presponse;        HTT presponse = client.execute(请求);
        。响应code = HTT presponse.getStatusLine()的getStatus code();
        消息= HTT presponse.getStatusLine()getReasonPhrase()。        HttpEntity实体= HTT presponse.getEntity();        如果(实体!= NULL){            InputStream的河道= entity.getContent();
            响应= convertStreamToString(插播广告);
            响应= StringUtils.remove(回应,\\ n);
            响应= StringUtils.remove(响应,'');
        }

有没有可能是我连接到服务只有一次的开始,接着是连接保持开放和应用不断,直到连接被关闭强行从服务中读取数据。结果
请让我知道,如果需要更多的code。

更新:然后我ClientConnectionManager试过,但还是连接连连初始化。虽然它获取数据。我想的是,连接保持开放,并不断从服务中读取数据。

的HttpParams httpParameters =新BasicHttpParams();

 共享preferences preferences = context.getShared preferences(
            我的preferences,Context.MODE_PRIVATE);    INT timeoutConnection =的Integer.parseInt(preferences.getString(
            超时,60))* 1000;
    HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);    HttpConnectionParams.setSoTimeout(httpParameters,2000年);
    System.setProperty(http.keepAlive,真);
    HttpClient的客户端=新DefaultHttpClient(httpParameters);    ClientConnectionManager经理= client.getConnectionManager();
    客户端=新DefaultHttpClient(新ThreadSafeClientConnManager(
            client.getParams(),mgr.getSchemeRegistry()),
            client.getParams());
    而(真){        HTT presponse HTT presponse;        尝试{
            HTT presponse = client.execute(请求);
            。响应code = HTT presponse.getStatusLine()的getStatus code();
            消息= HTT presponse.getStatusLine()getReasonPhrase()。            HttpEntity实体= HTT presponse.getEntity();            如果(实体!= NULL){                InputStream的河道= entity.getContent();
                响应= convertStreamToString(插播广告);
                响应= StringUtils.remove(回应,\\ n);
                响应= StringUtils.remove(响应,'');
                ((活动)上下文).runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        callback.run(响应); //这将调用活动回调函数。
                    }
                });                //关闭输入流会触发连接释放
                // instream.close();
            }        }赶上(ConnectTimeoutException E){
         ...。
         }


解决方案

这听起来像你真正需要的是一个socket连接(见的here )。套接字将保持连接,让你,直到你已完成了套接字服务器的数据流来回。

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(Bundle savedInstanceState) {  
….  
callWebMethod();
}  

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

This is how I am connecting to 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 connect to the service only once at the start, then the connection remains open and application keeps on reading data from service till connection is forcefully closed.
Please let me know if more code is required.

Update: I then tried with ClientConnectionManager but still connection is again and again initialising. Though it is getting data. What I want is that connection remains open, and keeps on reading data from 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) {
         ….  
         }

解决方案

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.

这篇关于保持连接打开,直到它被强制关闭读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆