以下代码是我的应用程序中的服务器代码:
private int serverPort;
private Thread serverThread = null;
public void networkListen(int port){
serverPort = port;
if (serverThread == null){
Runnable serverRunnable = new ServerRunnable();
serverThread = new Thread(serverRunnable);
serverThread.start();
} else {
}
}
public class ServerRunnable implements Runnable {
public void run(){
try {
//networkConnected = false;
//netMessage = "Listening for Connection";
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
ServerSocket serverSocket = new ServerSocket(serverPort, backlog);
commSocket = serverSocket.accept();
serverSocket.close();
serverSocket = null;
//networkConnected = true;
//netMessage = "Connected: " + commSocket.getInetAddress().getHostAddress() + ":" +
//commSocket.getPort();
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
} catch (IOException e){
//networkConnected = false;
//netMessage = "ServerRunnable Network Unavailable";
//System.out.println(e.getMessage());
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
}
}
}
代码类型的工作,即如果我尝试一个直接连接,两端通信和更新。
问题是,当我在监听连接时,如果我想退出监听,那么服务器线程将继续运行并导致问题。
我知道不应该在线程上使用.stop(),所以我想知道考虑到这个问题,解决方案会是什么样子?
编辑:注释掉了不需要的代码。