在使用数据报 channel 时,我得到一个 PortUnreachableException
。这就是我的代码的样子:
这是发送端
//Open a non-blocking socket to send data to Receiver
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(10000));
channel.connect(new InetSocketAddress(host,UDPort));
正是这段代码给我:java.net.PortUnreachableException
。参数“host”设置为:
String host = new String("192.168.1.3");
Receiver端是这样的
//Open a Socket to listen for incoming data
DatagramChannel channel = DatagramChannel.open();
channel.connect(new InetSocketAddress(UDPort));
channel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate((recvpkt[0].length)*4);
System.out.println("Waiting for packet");
channel.receive(buffer);
System.out.println("Received packet");
我不明白为什么会出现此异常。我在网上查找了示例,他们都建议代码应该是这样的。
更新 1:
正如 shazin 在评论中指出的那样,绑定(bind)需要在接收方完成,连接需要在发送方完成。发件人的更新代码是:
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(host,UDPort));
对于接收者:
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(host,UDPort));
现在的问题是,如果将“host”设置为“localhost”,程序可以运行,但如果我们将 IP 设置为 10.132.0.30 作为“host”,则会发生 java.net.PortUnreachableException
。当 channel.isConnected()
选项返回“true”时,channel.write(buffer) 命令给出异常。
更新 2:
PortUnreachableException
现在消失了。现在代码中的唯一区别是我使用选择器来接受接收器端的连接。我仍然不明白为什么没有使用选择器时会出现错误。如果有人无意中发现了这个问题并且知道了,请张贴您的答案。
最佳答案
尝试使用以下方法获取 IP 地址
channel.connect(new InetSocketAddress(InetAddress.getByName(host),UDPort));
UDPort 必须等于您在 Receiver 中用于绑定(bind)的端口。
关于java - 使用数据报 channel 时无法访问端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373394/