在AVD上运行时出现Android套接字错误

时间:2012-03-08 07:24:44

标签: java android android-layout sdk

我在以下代码的套接字中遇到问题,当我在AVD上运行程序时停止工作(不幸的是你的-app-停止了),我在Windows 7上使用Android 4.0平台。 我试图将套接字部分移动到按钮单击,所以当我单击按钮时程序停止工作,所以在套接字定义中出现错误。 (套接字套接字;)

public class ServerClient extends Activity {
// declaration of button, textView
private Button bt;
   private TextView tv;
  //port number
   private static final int REDIRECTED_SERVERPORT = 5000;
  //ip address
   private String serverIpAddress = "10.0.2.2";
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      bt = (Button) findViewById(R.id.myButton);
      tv = (TextView) findViewById(R.id.myTextView);

         // on click on the button the socket will be created
      bt.setOnClickListener(new OnClickListener() {

           Socket socket; //this line cause the app to stop working

         public void onClick(View v) {

          try {
             InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
             socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);

          } catch (UnknownHostException e1) {
             e1.printStackTrace();
          } catch (IOException e1) {
             e1.printStackTrace();
          }
            try {
               EditText et = (EditText) findViewById(R.id.EditText01);
               String str = et.getText().toString();
               PrintWriter out = new PrintWriter(new BufferedWriter(
                     new OutputStreamWriter(socket.getOutputStream())),
                     true);
               out.println(str);
               Log.d("Client", "Client sent message");

            } catch (UnknownHostException e) {
               tv.setText("Error1");
               e.printStackTrace();
            } catch (IOException e) {
               tv.setText("Error2");
               e.printStackTrace();
            } catch (Exception e) {
               tv.setText("Error3");
               e.printStackTrace();
            }
         }
      });
   }
}

3 个答案:

答案 0 :(得分:2)

您好我遇到了同样的问题(Windows 7,Android 4.03)。我已经使用android 2.33(API级别10)和使用android 2.33内核的模拟器解决了这个问题。

答案 1 :(得分:1)

您是否在AndroidManifest.xml中设置了互联网权限?

你需要这一行:

<uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:1)

您应该通过adb中的此命令将端口从PC转发到AVD:

adb forward tcp:YOUR_PORT_NUM tcp:YOUR_PORT_NUM