因为TCP保证数据包的传递,因此可以被认为是“可靠的”,而UDP不保证任何东西,数据包可能会丢失。在应用程序中使用UDP而不是TCP流传输数据的优势是什么?在什么情况下UDP是更好的选择,为什么?

我假设UDP更快,因为它没有创建和维护流的开销,但如果一些数据从未到达目的地,这不是无关紧要的吗?


当前回答

在某些情况下,保证数据包的到达并不重要,因此使用UDP是可以的。在其他情况下,UDP比TCP更可取。

你想要使用UDP而不是TCP的一个独特情况是你在另一个协议(例如隧道,虚拟网络等)上建立TCP隧道。如果您在TCP上建立隧道,则每个TCP的拥塞控制将相互干扰。因此,人们通常更喜欢在UDP(或其他无状态协议)上传输TCP。参见TechRepublic文章:理解TCP Over TCP: TCP隧道对端到端吞吐量和延迟的影响。

其他回答

UDP can be used when an app cares more about "real-time" data instead of exact data replication. For example, VOIP can use UDP and the app will worry about re-ordering packets, but in the end VOIP doesn't need every single packet, but more importantly needs a continuous flow of many of them. Maybe you here a "glitch" in the voice quality, but the main purpose is that you get the message and not that it is recreated perfectly on the other side. UDP is also used in situations where the expense of creating a connection and syncing with TCP outweighs the payload. DNS queries are a perfect example. One packet out, one packet back, per query. If using TCP this would be much more intensive. If you dont' get the DNS response back, you just retry.

这是我最喜欢的问题之一。UDP被误解了。

当你真的想快速地向另一个服务器得到一个简单的答案时,UDP是最好的选择。通常,您希望答案在一个响应包中,并准备实现自己的协议以提高可靠性或重新发送。DNS是这个用例的完美描述。连接设置的成本太高了(然而,DNS 不支持TCP模式以及)。

另一种情况是,当您交付的数据可能会丢失,因为新的数据将取代之前的数据/状态。天气数据、视频流、股票报价服务(不用于实际交易)或游戏数据浮现在脑海中。

另一种情况是,当您正在管理大量的状态时,您希望避免使用TCP,因为操作系统无法处理那么多会话。这在今天是一个罕见的案例。事实上,现在可以使用用户专用的TCP堆栈,以便应用程序编写人员可以对该TCP状态所需的资源进行更细粒度的控制。在2003年之前,UDP是唯一的游戏。

另一种情况是多播流量。UDP可以多播到多个主机,而TCP根本不能这样做。

比较TCP和UDP,像UDP这样的无连接协议可以保证速度,但不能保证数据包传输的可靠性。 例如,电子游戏通常不需要可靠的网络,但速度是最重要的,在游戏中使用UDP具有减少网络延迟的优势。

只使用UDP,如果你真的知道你在做什么。UDP在今天是在极其罕见的情况下,但数量(甚至非常有经验)专家谁会试图坚持到处似乎是不成比例。也许他们喜欢自己实现错误处理和连接维护代码。

由于所谓的校验和印记,使用现代网络接口卡,TCP应该会快得多。令人惊讶的是,在快速连接速度下(比如1Gbps),计算校验和对CPU来说是一个很大的负载,所以它被卸载到识别TCP数据包的NIC硬件上,它不会为你提供相同的服务。

We have web service that has thousands of winforms client in as many PCs. The PCs have no connection with DB backend, all access is via the web service. So we decided to develop a central logging server that listens on a UDP port and all the clients sends an xml error log packet (using log4net UDP appender) that gets dumped to a DB table upon received. Since we don't really care if a few error logs are missed and with thousands of client it is fast with a dedicated logging service not loading the main web service.