Java + UDP + DatagramSocket : Why is a PortUnreachableException thrown, 当 UDP 被设计为无连接时?

标签 java networking udp

当 UDP 本身被设计为无连接时,我无法理解为什么在 Java 中可以从 DatagramSocket 抛出 PortUnreachableException。我对UDP的理解是,当数据包无法传送时就会被丢弃。为什么使用 DatagramSocket 实现 UDP 的 Java 会提供有关数据包传送的反馈?

最佳答案

在这种情况下,“无连接”是指 UDP 不进行握手来建立连接。而且,除非服务器协议(protocol)设计为发送数据包,否则不会确认收到发送的数据包,因此 UDP 确实具有连接的套接字。不是同一件事。

虽然 DatagramSocket 有一个 connect 方法,但 API 声明:

If the remote destination to which the socket is connected does not exist, or is otherwise unreachable, and if an ICMP destination unreachable packet has been received for that address, then a subsequent call to send or receive may throw a PortUnreachableException. Note, there is no guarantee that the exception will be thrown.

因此,您有可能将数据发送到某个地址,但没有任何迹象表明实际上没有连接。

这一切都取决于操作系统的实现,例如在 Linux 中,有一种方法可以建立连接来优化路由 http://man7.org/linux/man-pages/man7/udp.7.html#DESCRIPTION 提高性能,因为 UDP 不代表 future 的路由,因此如果提前调用 connect 它将能够显着提高性能 您可以阅读有关此的更多信息 in this answer专门研究 Linux 中的 UDP

关于Java + UDP + DatagramSocket : Why is a PortUnreachableException thrown, 当 UDP 被设计为无连接时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630718/

相关文章:

java - Spring Web Flow 中快照和流存储库的最佳文档是什么?

networking - 如何捕获单个 docker 容器的数据包

c - 我已经使用 ifconfig 将以太网和 Wifi 设置为混杂模式,但我仍然只收到来自和发送到我的计算机的数据包

c# - UdpClient.() 与 UdpClient(端口)

ios - Swift-UDP接收和发送

java - 如何在runnable中实现回调来更新其他swing类

java - 如何使用 java 集合随机播放文件 []?

c++ - 两台计算机与 2 个 c++ 程序之间的通信

c++ - UDP Tx 循环每次在正好 3970 个数据包时停止工作,在我 friend 的计算机上为 14386

java - 增加线程数量是否会使生产者消费者概率更快?