java 在程序终止的情况下如何关闭端口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/767292/
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
How do I close a port in a case of program termination?
提问by Chathuranga Chandrasekara
I am using Socket communication in one of my Java applications.As I know if the program meets any abnormal termination the listening ports does not get closed and the program cannot be started back because it reports "Port already open.." Do I have anyway to handle this problem? What is the general way used to handle this matter?
我在我的一个 Java 应用程序中使用 Socket 通信。据我所知,如果程序遇到任何异常终止,侦听端口不会关闭并且程序无法重新启动,因为它报告“端口已经打开......”我有吗处理这个问题?处理此事的一般方式是什么?
回答by Greg Hewgill
It sounds like your program is listening on a socket. Normally, when your program exits the OS closes all sockets that might be open (including listening sockets). However, for listening sockets the OS normally reserves the port for some time (several minutes) after your program exits so it can handle any outstanding connection attempts. You may notice that if you shut down your program abnormally, then come back some time later it will start up just fine.
听起来您的程序正在侦听套接字。通常,当您的程序退出时,操作系统会关闭所有可能打开的套接字(包括侦听套接字)。但是,对于侦听套接字,操作系统通常会在程序退出后保留端口一段时间(几分钟),以便它可以处理任何未完成的连接尝试。您可能会注意到,如果您异常关闭程序,稍后再返回它会正常启动。
If you want to avoid this delay time, you can use setsockopt()to configure the socket with the SO_REUSEADDR option. This tells the OS that you know it's OK to reuse the same address, and you won't run into this problem.
如果你想避免这个延迟时间,你可以使用setsockopt()SO_REUSEADDR 选项来配置套接字。这告诉操作系统您知道可以重用相同的地址,并且您不会遇到这个问题。
You can set this option in Java by using the ServerSocket.setReuseAddress(true)method.
您可以使用ServerSocket.setReuseAddress(true)方法在 Java 中设置此选项。
回答by James Davies
You want to set the SO_REUSEADDR flag on the socket
您想在套接字上设置 SO_REUSEADDR 标志
See http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#setReuseAddress(boolean)
见http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#setReuseAddress(boolean)
回答by Esko Luontola
The operating system should handle things such as that automatically, when the JVM process has ended. There might be a short delay before the port is closed, though.
当 JVM 进程结束时,操作系统应该自动处理诸如此类的事情。不过,在端口关闭之前可能会有短暂的延迟。
回答by VonC
As mentioned in the Handling abnormal Java program exits, you could setup a Runtime.addShutdownHook()method to deals with any special case, if it really needs an explicit operation.
如处理异常 Java 程序退出中所述,您可以设置Runtime.addShutdownHook()方法来处理任何特殊情况,如果它确实需要显式操作。

