Java + UDP + DatagramSocket:当 UDP 设计为无连接时,为什么抛出 PortUnreachableException?

Java + UDP + DatagramSocket: Why is a PortUnreachableException thrown, when UDP is designed to be connection-less?

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

在这种情况下,"connection-less" 指的是 UDP 不通过握手来建立连接。而且,除非服务器协议被设计为发送它们,否则不会确认收到已发送的数据包,因此 UDP 确实有连接的套接字。不是一回事。

虽然 DatagramSocket 有连接方法,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.

因此,您可以将数据发送到一个地址,但没有指示实际上没有连接。

这一切都取决于 OS 实现,例如 Linux 有一种方法可以建立连接以优化路由 http://man7.org/linux/man-pages/man7/udp.7.html#DESCRIPTION 提高性能,因为 UDP 没有未来的路由,所以如果事先调用连接,它将能够显着提高性能 您可以在 Linux

中阅读更多关于此 in this answer 的内容,具体了解 UDP