在使用Datagram 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");
接收方是这边。
//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在评论中指出的那样,绑定需要在接收方进行,连接需要在发送方进行。发送方的更新后的代码如下:
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现在已经消失了。现在代码中唯一的区别是我正在使用选择器来接受接收器端的连接。我仍然不明白为什么在不使用选择器的情况下会出现错误。如果有人遇到这个问题并知道原因,请发表您的答案。