我正在使用本教程建立客户端服务器连接。我面临的问题是它不会停止,Log cat 继续显示客户端在无限循环中发送数据。服务器也在无限循环中接收此数据
这是我的代码
任何建议/更改都将不胜感激,我被困在这个问题上,昨天无法从谷歌那里得到一个好的工作解决方案。
谢谢
编辑
客户端代码
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println(serverIpAddress);
//connected = false;
//socket.close();
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
服务器端
public class ServerThread implements Runnable {
private volatile boolean keepGoing = true;
private volatile boolean firstLoop = true;
public void requestStop() {
keepGoing = false;
}
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (keepGoing) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText(line);
Log.d("IP recevied", line);
requestStop();
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted.
Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}