我使用以下代碼連接兩個Android設備P2P。問題是,當服務器從客戶端接收數據時,其Thread/Runable不會停止。Android/Java實現Runable進入無限循環
請建議我一種方法來阻止/強迫它進入無限循環。
下面是一段代碼,我用我的服務器活動時間:
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
}
});
}
將'while(true)'改爲'while(keepGoing)'? – hmjd
它仍然沒有工作:( –