Java 停止服务器线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2804797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Stop Server Thread
提问by iTEgg
the following code is server code in my app:
以下代码是我的应用程序中的服务器代码:
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);
}
}
}
The code sort of works i.e. if im attempting a straight connection both ends communicate and update.
代码排序工作,即如果我尝试直接连接两端通信和更新。
The issue is while im listening for a connection if i want to quit listening then the server thread continues running and causes problems.
问题是当我在侦听连接时,如果我想退出侦听,则服务器线程继续运行并导致问题。
i know i should not use .stop() on a thread so i was wondering what the solution would look like with this in mind?
我知道我不应该在线程上使用 .stop() 所以我想知道解决方案会是什么样的?
EDIT: commented out unneeded code.
编辑:注释掉不需要的代码。
回答by RedPandaCurios
Close the server socket from an external thread. As per the documentation on Serversocket.close()the blocking accept will throw a SocketException and you can shutdown your thread.
从外部线程关闭服务器套接字。根据Serversocket.close()上的文档,阻塞接受将抛出 SocketException 并且您可以关闭您的线程。
回答by Jonathon Faust
After initializing your ServerSocket, use setSoTimeout. Put the accept in a loop, catching the timeouts. Break from the loop and return from runbased on whether you want to continue or not.
初始化 ServerSocket 后,使用setSoTimeout。将接受放入循环中,捕捉超时。run根据您是否要继续,从循环中退出并返回。

