【发布时间】:2012-03-08 07:24:43
【问题描述】:
我在以下代码的套接字中遇到问题,当我在 AVD 上运行程序时,它导致程序停止工作(不幸的是,您的 -app- 已停止),我在 Windows 7 上使用 Android 4.0 平台 .. 我试图将套接字部分移动到按钮单击,所以当我单击按钮时程序停止工作,所以在套接字定义中出现错误。 (Socket 插座;)
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();
}
}
});
}
}
【问题讨论】:
标签: java android android-layout sdk