1

我是android开发的初学者,

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

  • 使用 ip 和端口连接到特定的 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());

   }

但这通常在服务器不可用时挂起。有解决办法吗?

4

1 回答 1

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


}
于 2013-10-30T12:21:50.317 回答