java 如何在java代码中为数据报套接字设置重用地址选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7832393/
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 to set reuse address option for a datagram socket in java code?
提问by Suman
In my application there will be one thread which always be running and will be sending or listening to some port.
在我的应用程序中,将有一个始终运行的线程,并将发送或侦听某个端口。
This application runs in the background. Sometimes while creating the socket, i found that the port which was used by the same thread before, is not getting released on close() of the socket. So i tried like this
此应用程序在后台运行。有时在创建套接字时,我发现之前由同一线程使用的端口没有在套接字的 close() 上释放。所以我试过这样
dc = new DatagramSocket(inetAddr);
dc.setReuseAddress(true);
The problem is , it is not reaching to the second line also. in the first line itself i am getting the expcetion BindException: Address already in use
.
问题是,它也没有到达第二行。在第一行本身,我得到了 expcetion BindException: Address already in use
。
Can anyone please help me how to handle this is situation.
任何人都可以帮助我如何处理这种情况。
Is there any way to release the port ?
有没有办法释放端口?
Thanks & Regards,
SSuman185
感谢和问候,
SSuman185
采纳答案by user207421
Use a MulticastSocket
. Construct it with no arguments. That implicitly calls setReuseAddress(true). Then call bind().
使用一个MulticastSocket
. 构造它没有参数。这隐式调用 setReuseAddress(true)。然后调用bind()。
At the moment you are calling setReuseAddress() too late for it to do any good.
目前你调用 setReuseAddress() 太晚了,它没有任何好处。
回答by poy
DatagramSocket(inetAddr)
binds to the port. You need to setReuseAddress(true)
BEFORE you bind.
DatagramSocket(inetAddr)
绑定到端口。你需要setReuseAddress(true)
在绑定之前。
To do this... use the following:
要做到这一点......使用以下内容:
dc = new DatagramSocket(null);
dc.setReuseAddress(true);
dc.bind(inetAddr);
This constructor leaves the port unbound.
此构造函数使端口未绑定。
回答by Moti Bartov
This is how it worked for me:
这对我来说是这样的:
try {
clientMulticastSocket = new MulticastSocket(null);
clientMulticastSocket.setReuseAddress(true);
clientMulticastSocket.bind(new InetSocketAddress(multicastHostAddress, multicastPort));
clientMulticastSocket.joinGroup(multicastHostAddress);
} catch (IOException e) {
e.printStackTrace();
return false;
}