我创建了一个SMTPServer(带有Java.NIO),它正在运行while循环并处理传入的客户端。我想添加一个Shutdownhook退出while循环并关闭所有打开的选择器Sockest。等等,并用退出代码0结束程序。但是我不太了解如何在代码中使用shutdownhook。
public class SMTPServer {
private static volatile boolean keepRunning = true;
private static methode1 {}
private static methode2 {}
private static methode3 {}
public static void main(String[] args) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
Selector selector = Selector.open();
...
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
keepRunning = false;
}
});
...
while(keepRunning) {
if (selector.select() == 0)
continue;
here I handle the Client
}
selector.close();
ssc.close();
System.out.println("Server offline");
System.exit(0);
}
}
我想,当我在IntelliJ中退出程序时,它将跳出while循环,因为我将keepRunning更改为false,并且将使用while之后的代码。