Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

android - How to set reuse address option for a datagram socket in java code?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...