java – 使用数据报通道时无法访问端口

使用数据报通道时,我得到一个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的评论中指出的那样,绑定需要在Receiver和Sender的连接上完成. Sender的更新代码是:

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现在消失了.现在代码的唯一区别是我使用选择器来接受Receiver端的连接.我仍然不明白为什么在没有使用选择器时出现错误.如果有人在这个问题上发现并且知道,请发布你的答案.

最佳答案 尝试使用以下内容获取IP地址

channel.connect(new InetSocketAddress(InetAddress.getByName(host),UDPort));

UDPort必须等于您在Receiver中绑定的端口.

点赞