gpt4 book ai didi

java - 如何以正确的方式关闭套接字?

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:41 25 4
gpt4 key购买 nike

这是一个简单的 TCP 服务器。当程序终止时如何关闭套接字?我使用 try/finally 并尝试关闭套接字。但是当我退出程序时它不会运行finally block 。

任何人都可以知道如何以正确的方式关闭套接字?

try {
socket = new ServerSocket(port);
System.out.println("Server is starting on port " + port + " ...");
}catch (IOException e){
System.out.println("Error on socket creation!");
}

Socket connectionSocket = null;
try{
while(true){
try{
connectionSocket = socket.accept();
Thread t = new Thread(new ClientConnection(connectionSocket));
t.start();
}catch (IOException e) {
System.out.println("Error on accept socket!");
}
}
}finally{
this.socket.close();
System.out.println("The server is shut down!");
}

最佳答案

创建 ServerSocket 后,您可以添加 ShutdownHook在 JVM 终止时关闭它,如下所示:

Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){
try {
socket.close();
System.out.println("The server is shut down!");
} catch (IOException e) { /* failed */ }
}});

调用ServerSocket#close将终止阻止 ServerSocket.accept调用,导致它抛出 SocketException。但是,请注意,当前在 while 循环中对 IOException 的处理意味着您将重新进入 while 循环以尝试在关闭的套接字上接受。 JVM 仍然会终止,但有点不整洁。

如果您在 Eclipse 中终止控制台应用程序(至少在 Windows 上),关闭 Hook 不会运行。但如果您在普通控制台中按 CTRL-C Java,它们就会运行。为了让它们运行,您需要正常终止 JVM,例如SIGINT 或 SIGTERM 而不是 SIGKILL (kill -9)。

可以在 Eclipse 或控制台中执行的一个简单程序将演示这一点。

public class Test implements Runnable {

public static void main(String[] args) throws InterruptedException {
final Test test = new Test();
Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){
test.shutdown();
}});
Thread t = new Thread(test);
t.start();
}

public void run() {
synchronized(this) {
try {
System.err.println("running");
wait();
} catch (InterruptedException e) {}
}
}

public void shutdown() {
System.err.println("shutdown");
}
}

关于java - 如何以正确的方式关闭套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56111484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com