如何在java代码中为数据报套接字设置重用地址选项?

发布于 2024-12-11 02:56:36 字数 383 浏览 0 评论 0原文

在我的应用程序中,将有一个线程始终运行并将发送或侦听某个端口。

该应用程序在后台运行。有时在创建套接字时,我发现之前由同一线程使用的端口在套接字的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦在深巷 2024-12-18 02:56:36

DatagramSocket(inetAddr) 绑定到端口。您需要在绑定之前setReuseAddress(true)

为此...使用以下命令:

dc = new DatagramSocket(null);
dc.setReuseAddress(true);
dc.bind(inetAddr);

此构造函数使端口处于未绑定状态。

DatagramSocket(inetAddr) binds to the port. You need to setReuseAddress(true) BEFORE you bind.

To do this... use the following:

dc = new DatagramSocket(null);
dc.setReuseAddress(true);
dc.bind(inetAddr);

This constructor leaves the port unbound.

很快妥协 2024-12-18 02:56:36

使用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.

凉城已无爱 2024-12-18 02:56:36

这对我来说是这样的:

try {
      clientMulticastSocket = new MulticastSocket(null);
      clientMulticastSocket.setReuseAddress(true);
      clientMulticastSocket.bind(new InetSocketAddress(multicastHostAddress, multicastPort));
      clientMulticastSocket.joinGroup(multicastHostAddress);
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }

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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文