Java ServerSocket 中 setReuseAddress 的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23123395/
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
What is the purpose of setReuseAddress in ServerSocket?
提问by Chaitanya
I have a simple logic Java that checks if a port is already in use or not:
我有一个简单的逻辑 Java 来检查端口是否已在使用中:
public static boolean isPortInUse(int port)
{
ServerSocket socket = null;
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
} catch (Exception e) {
return true;
}
finally
{
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
return true;
}
}
}
return false;
}
I am new to socket programming so I am not able to understand what is the use of the method "setReuseAddress"
here. I have gone through this linkbut I am not getting clarity the purpose of it.
我是套接字编程的新手,所以我无法理解"setReuseAddress"
这里方法的用途。我已经浏览了这个链接,但我没有弄清楚它的目的。
采纳答案by Koitoer
This explanation is coming from TCP mechanism involving some low level socket properties and protocols, basically there is an option called SO_REUSEADDR that you define when you are creating the socket, using the method setReuseAddress()enable or disable this behavior.
这个解释来自涉及一些低级套接字属性和协议的 TCP 机制,基本上有一个名为 SO_REUSEADDR 的选项,您在创建套接字时定义它,使用方法setReuseAddress()启用或禁用此行为。
The current explanation is very well defined here, take a look there. Also APIhave very good explanation
当前的解释在这里定义得很好,看看那里。此外API有很好的解释
Just take as a configuration parameter that can be modified using that method.
只需将其作为可以使用该方法修改的配置参数即可。
Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.
在使用 bind(SocketAddress) 绑定套接字之前启用 SO_REUSEADDR 允许绑定套接字,即使先前的连接处于超时状态。