Exception in thread “main“ java.net.BindException: Address already in use: Cannot bind.
IDEA:Exception in thread “main” java.net.BindException: Address already in use: Cannot bind出现的可能情况
·
IDEA:Exception in thread “main” java.net.BindException: Address already in use: Cannot bind出现的可能情况
在学习Java的UDP通讯程序练习的时候,我在接收数据时写了如下代码:
package UDP通信程序练习;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
while (true) {
DatagramSocket ds = new DatagramSocket(25555);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
ds.receive(dp);
System.out.println("数据是:" + new String(dp.getData(), 0, dp.getLength()));
}
}
}
然后同时运行接收和发送数据时,发送数据出现了这样的问题:
端口占用可能原因:
该博主的博客说明了两种可能的原因和解决方法
但是查看对照以后 甚至重启 我的问题依然没有解决。
于是我再次阅读我的代码发现了关键问题在于我创建DatagromSocket时将 其放在了循环里面,这就导致了这个端口被多次使用,造成了端口占用问题。所以只需要把以下语句放在循环外即可。(端口自定义
DatagramSocket ds = new DatagramSocket(25555);
修改后的代码:
package UDP通信程序练习;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(25555);
while (true) {
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
ds.receive(dp);
System.out.println("数据是:" + new String(dp.getData(), 0, dp.getLength()));
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)