用于一般协议消息交换,可以容忍一定的丢包。UDP比TCP效率高多少?


当前回答

如果不考虑网络情况,只讨论TCP或UDP是没有意义的。 如果两点之间的网络质量非常高,UDP绝对比TCP快,但在其他一些情况下,如GPRS网络,TCP可能比UDP更快,更可靠。

其他回答

请记住,TCP通常在网络上保存多条消息。如果你想在UDP中实现这一点,如果你想可靠地做到这一点,你将有相当多的工作。你的解决方案要么不太可靠,要么速度较慢,要么工作量巨大。有有效的UDP应用程序,但如果你问这个问题,你的可能不是。

具有容错功能

你是说“容忍损失”吗?

基本上,UDP不是“容错”的。你可以发送100个包给某人,他们可能只收到其中的95个包,有些包的顺序可能是错误的。

对于视频流媒体和多人游戏之类的东西,错过一个数据包总比延迟它后面的所有其他数据包要好,这是显而易见的选择

然而,对于大多数其他事情,丢失或“重新排列”的数据包是至关重要的。你必须编写一些额外的代码来运行在UDP之上,以便在遗漏内容时重试,并强制执行正确的顺序。这在某些地方会增加一点开销。

值得庆幸的是,一些非常非常聪明的人已经做到了这一点,他们称之为TCP。

可以这样想:如果一个数据包丢失了,您是希望尽快获得下一个数据包并继续(使用UDP),还是您实际上需要丢失的数据(使用TCP)。开销并不重要,除非你在一个真正的边缘情况下。

网络的设置对于任何测量都是至关重要的。如果您通过本地机器上的套接字或与世界的另一端进行通信,则会产生巨大的差异。

我想在讨论中补充三点:

您可以在这里找到一篇关于TCP与UDP的非常好的文章 游戏开发的背景。 此外,iperf (jperf增强iperf与GUI)是一个 这是一个很好的工具,可以通过测量来回答你的问题。 我用Python实现了一个基准测试(参见这个SO问题)。在平均10^6次迭代中,UDP发送8字节的差异大约是1-2微秒。

Which protocol performs better (in terms of throughput) - UDP or TCP - really depends on the network characteristics and the network traffic. Robert S. Barnes, for example, points out a scenario where TCP performs better (small-sized writes). Now, consider a scenario in which the network is congested and has both TCP and UDP traffic. Senders in the network that are using TCP, will sense the 'congestion' and cut down on their sending rates. However, UDP doesn't have any congestion avoidance or congestion control mechanisms, and senders using UDP would continue to pump in data at the same rate. Gradually, TCP senders would reduce their sending rates to bare minimum and if UDP senders have enough data to be sent over the network, they would hog up the majority of bandwidth available. So, in such a case, UDP senders will have greater throughput, as they get the bigger pie of the network bandwidth. In fact, this is an active research topic - How to improve TCP throughput in presence of UDP traffic. One way, that I know of, using which TCP applications can improve throughput is by opening multiple TCP connections. That way, even though, each TCP connection's throughput might be limited, the sum total of the throughput of all TCP connections may be greater than the throughput for an application using UDP.

UDP比TCP快,原因很简单,因为它不存在允许连续数据包流的确认数据包(ACK),而不是使用TCP窗口大小和往返时间(RTT)来确认一组数据包的TCP。

要了解更多信息,我推荐简单但非常容易理解的Skullbox解释(TCP vs. UDP)