如何在java代码中为数据报套接字设置重用地址选项?
在我的应用程序中,将有一个线程始终运行并将发送或侦听某个端口。
该应用程序在后台运行。有时在创建套接字时,我发现之前由同一线程使用的端口在套接字的 close() 上没有被释放。所以我尝试了这样的
dc = new DatagramSocket(inetAddr);
dc.setReuseAddress(true);
问题是,它也没有到达第二行。在第一行本身中,我得到了表达式 BindException: Address already in use
。
谁能帮助我如何处理这种情况。
有什么办法可以释放端口吗?
谢谢&问候,
S苏曼185
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
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
.
Can anyone please help me how to handle this is situation.
Is there any way to release the port ?
Thanks & Regards,
SSuman185
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DatagramSocket(inetAddr)
绑定到端口。您需要在绑定之前setReuseAddress(true)
。为此...使用以下命令:
此构造函数使端口处于未绑定状态。
DatagramSocket(inetAddr)
binds to the port. You need tosetReuseAddress(true)
BEFORE you bind.To do this... use the following:
This constructor leaves the port unbound.
使用
MulticastSocket
。不带参数构造它。这隐式调用 setReuseAddress(true)。然后调用bind()。目前你调用 setReuseAddress() 已经太晚了,它没有任何好处。
Use a
MulticastSocket
. Construct it with no arguments. That implicitly calls setReuseAddress(true). Then call bind().At the moment you are calling setReuseAddress() too late for it to do any good.
这对我来说是这样的:
This is how it worked for me: