Android开发中Socket通信的基本实现方法讲解

  package my.learn.tcp;

  import java.io.BufferedReader;

  import java.io.IOException;

  import java.io.InputStreamReader;

  import java.net.Socket;

  import java.net.UnknownHostException;

  import android.app.Activity;

  import android.os.Bundle;

  import android.util.Log;

  import android.widget.EditText;

  public class SimpleClient extends Activity {

  private EditText show;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  // TODO Auto-generated method stub

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  show = (EditText) findViewById(R.id.show);

  try {

  Socket socket = new Socket("自己计算机的IP地址", 30000);

  //设置10秒之后即认为是超时

  socket.setSoTimeout(10000);

  BufferedReader br = new BufferedReader(new InputStreamReader(

  socket.getInputStream()));

  String line = br.readLine();

  show.setText("来自服务器的数据:"+line);

  br.close();

  socket.close();

  } catch (UnknownHostException e) {

  // TODO Auto-generated catch block

  Log.e("UnknownHost", "来自服务器的数据");

  e.printStackTrace();

  } catch (IOException e) {

  Log.e("IOException", "来自服务器的数据");

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  }

  }