How to set reuse address parameter for datagram socket in java code?

In my application there will be one thread that will always work and will send or listen to any port.

This app runs in the background. Sometimes when creating a socket, I find that the port that was used by the same thread before is not freed when the socket is closed (). So I tried like this

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

The problem is that it does not reach the second line either. in the first line I get expcetion BindException: Address already in use.

Can someone help me how to deal with this situation.

Is there any way to free the port?

Thanks and Regards,
SSuman185

+5
3

MulticastSocket. . setReuseAddress (true). bind().

, setReuseAddress() , - .

+6

DatagramSocket(inetAddr) . setReuseAddress(true) .

... :

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

.

+11

Here's 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;
    }
0
source

All Articles