我正在开发一个简单的聊天应用程序。Android 客户端和 java 桌面服务器。我面临一个问题,我的客户端只向服务器发送一条消息。服务器代码在 java 客户端上工作,所以只有 android 代码有一些问题。安卓客户端
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
private Socket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
EditText et = (EditText) findViewById(R.id.editText1);
public void onClick(View v) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
String str = et.getText().toString();
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}