异步任务:连接到tcp服务器并发送字符串,关闭连接

时间:2013-10-30 12:00:22

标签: java android tcpclient

我是android开发的初学者,

使用异步任务单击按钮时,我必须执行以下操作。

  • 使用ip和Port连接到特定的TCP服务器并检查其是否已连接? 失败时显示祝酒消息
  • 成功时将字符串发送到tcp服务器
  • 关闭连接。

我使用下面的代码连接

  try
  {
     s= new Socket("192.168.43.205",20108);
     out = new BufferedWriter( new OutputStreamWriter(s.getOutputStream()));
     BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

  }
  catch (UnknownHostException e) {
     tv.setText(e.toString());
     Log.v("Tcp", e.toString());
   } 
   catch (IOException e) {
      tv.setText(e.toString());
      Log.v("Tcp",e.toString());
   }
   catch (Exception e) {
      tv.setText(e.toString());

   }

但是当服务器不可用时,这通常会挂起。有没有解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用AsyncTask建立连接和检索数据

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.os.AsyncTask;

public class SendDataAsync extends AsyncTask<String, Void, String> {

    Context mContext;

    public SendDataAsync(Context context){
        this.mContext = context;
    }

    @Override
    protected String doInBackground(String... params) {

        String str = params[0];
            .
            .
            .

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("YOUR_URL");
        httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
        BasicNameValuePair strBasicNameValuePair = new BasicNameValuePair("str", str);
            .
            .
            .


        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(strBasicNameValuePair);
            .
            .
            .


        try {

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);

            try {

                HttpResponse httpResponse = httpClient.execute(httpPost);
                InputStream  inputStream = httpResponse.getEntity().getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuilder stringBuilder = new StringBuilder();
                String  bufferedStrChunk = null;
                while((bufferedStrChunk = bufferedReader.readLine()) != null){
                    stringBuilder.append(bufferedStrChunk);
                }

                return stringBuilder.toString();

            } catch (ClientProtocolException cpe) {
                System.out.println("Client Protocol Exception :" + cpe);
                cpe.printStackTrace();
            } catch (IOException ioe) {
                System.out.println("IO Exception :" + ioe);
                ioe.printStackTrace();
            }

        } catch (UnsupportedEncodingException uee) {
            System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
            uee.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        this.cancel(true);
    }


}