我正在使用以下代码连接两个 Android 设备 P2P。问题是,当服务器从客户端接收数据时,它的 Thread/Runnable 不会停止。
请建议我一种方法来停止/强制它进入无限循环。
以下是我用于服务器活动的一段代码:
public class ServerThread implements Runnable {
private volatile boolean keepGoing = 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 (true) {
// 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();
//finish();
//Intent i = new Intent(ServerActivity.this,
//ClientActivity.class);
//startActivity(i);
//serverStatus.setText(line);
// do whatever you want to the front end
// this is where you can be creative
}
});
}
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();
}
}
}
编辑:
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) && keepGoing) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText(line);
Log.d("IP recevied", line);
requestStop();
//finish();
//Intent i = new Intent(ServerActivity.this,
//ClientActivity.class);
//startActivity(i);
//serverStatus.setText(line);
// do whatever you want to the front end
// this is where you can be creative
}
});
}