首页 > 代码库 > android java.net.BindException: bind failed: EADDRINUSE (Address already in use)

android java.net.BindException: bind failed: EADDRINUSE (Address already in use)

今天遇到一种情况,在手机上发广播包,在4.4.2上的手机会发生,4.1.2和4.0.2都没有遇见,问题是这样的


try{

DatagramSocket udpSocket = new DatagramSocket(DEFAULT_PORT );

} catch (Exception e)

{

e.printStackTrace();

}

//java.net.BindException: bind failed: EADDRINUSE (Address already in use)



解决方法:
将:udpSocket = new DatagramSocket(DEFAULT_PORT );
改为:
if(udpSocket==null){
udpSocket = new DatagramSocket(null);
udpSocket.setReuseAddress(true);
udpSocket.bind(new InetSocketAddress(DEFAULT_PORT));
}

问题就解决了


android java.net.BindException: bind failed: EADDRINUSE (Address already in use)