因为TCP保证数据包的传递,因此可以被认为是“可靠的”,而UDP不保证任何东西,数据包可能会丢失。在应用程序中使用UDP而不是TCP流传输数据的优势是什么?在什么情况下UDP是更好的选择,为什么?
我假设UDP更快,因为它没有创建和维护流的开销,但如果一些数据从未到达目的地,这不是无关紧要的吗?
因为TCP保证数据包的传递,因此可以被认为是“可靠的”,而UDP不保证任何东西,数据包可能会丢失。在应用程序中使用UDP而不是TCP流传输数据的优势是什么?在什么情况下UDP是更好的选择,为什么?
我假设UDP更快,因为它没有创建和维护流的开销,但如果一些数据从未到达目的地,这不是无关紧要的吗?
当前回答
UDP具有较低的开销,如前所述,它对视频和音频等流媒体很好,最好只是丢失一个数据包,然后尝试重新发送和追赶。
TCP传输没有保证,你只是被告知套接字是否断开,或者数据是否没有到达。否则它会在到达目的地的时候到达目的地。
A big thing that people forget is that udp is packet based, and tcp is bytestream based, there is no guarantee that the "tcp packet" you sent is the packet that shows up on the other end, it can be dissected into as many packets as the routers and stacks desire. So your software has the additional overhead of parsing bytes back into usable chunks of data, that can take a fair amount of overhead. UDP can be out of order so you have to number your packets or use some other mechanism to re-order them if you care to do so. But if you get that udp packet it arrives with all the same bytes in the same order as it left, no changes. So the term udp packet makes sense but tcp packet doesnt necessarily. TCP has its own re-try and ordering mechanism that is hidden from your application, you can re-invent that with UDP to tailor it to your needs.
UDP更容易在两端编写代码,基本上是因为你不需要建立和维护点到点连接。我的问题是在什么情况下你需要TCP开销?如果你走捷径,比如假设接收到的tcp“数据包”是发送的完整数据包,你会更好吗?(如果你费心检查长度/内容,你可能会扔掉两个包)
其他回答
请参阅Steven的Unix网络编程的22.4节,“何时使用UDP而不是TCP”。
另外,请参阅关于UDP总是比TCP更快的误解的其他SO回答。
史蒂文的话可以总结如下:
使用UDP广播和组播,因为这是你唯一的选择(任何新的应用程序使用组播) 你可以在简单的请求/回复应用中使用UDP,但你需要构建自己的ack、超时和重传 不要使用UDP进行批量数据传输。
UDP确实有更少的开销,适合做一些事情,比如流式实时数据,如音频或视频,或者在任何情况下,如果数据丢失是ok的。
比较TCP和UDP,像UDP这样的无连接协议可以保证速度,但不能保证数据包传输的可靠性。 例如,电子游戏通常不需要可靠的网络,但速度是最重要的,在游戏中使用UDP具有减少网络延迟的优势。
视频流是使用UDP的一个很好的例子。
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.