什么时候适合使用UDP而不是TCP?

发布于 2024-07-26 00:17:43 字数 1552 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

他夏了夏天 2024-08-02 00:17:44

它并不总是明确的。 但是,如果您需要保证以正确的顺序无丢失地传送数据包,那么 TCP 可能就是您想要的。

另一方面,UDP 适合传输短信息包,其中信息的顺序不太重要,或者数据可以放入单个信息包中。
包。

当您想要向许多用户广播相同的信息时,它也很合适。

其他时候,当您发送排序数据时这是合适的,但如果其中一些数据丢失了
错过你不太关心(例如VOIP应用程序)。

有些协议更复杂,因为需要 TCP 的一些(但不是全部)功能,但比 UDP 提供的功能更多。 这就是应用层必须要做的事情
实现附加功能。 在这些情况下,UDP 也是合适的(例如网络广播,顺序很重要,但并非每个数据包都需要通过)。

它在哪里/可以使用的示例
1) 时间服务器向 LAN 上的一堆机器广播正确的时间。
2) 网络电话协议
3)DNS查询
4) 请求 LAN 服务,例如您在哪里?
5) 网络广播
6) 以及许多其他...

在 unix 上,您可以输入 grep udp /etc/services 来获取已实现的 UDP 协议列表
今天……有数百个。

It's not always clear cut. However, if you need guaranteed delivery of packets with no loss and in the right sequence then TCP is probably what you want.

On the other hand UDP is appropriate for transmitting short packets of information where the sequence of the information is less important or where the data can fit into a single
packet.

It's also appropriate when you want to broadcast the same information to many users.

Other times, it's appropriate when you are sending sequenced data but if some of it goes
missing you're not too concerned (e.g. a VOIP application).

Some protocols are more complex because what's needed are some (but not all) of the features of TCP, but more than what UDP provides. That's where the application layer has to
implement the additional functionality. In those cases, UDP is also appropriate (e.g. Internet radio, order is important but not every packet needs to get through).

Examples of where it is/could be used
1) A time server broadcasting the correct time to a bunch of machines on a LAN.
2) VOIP protocols
3) DNS lookups
4) Requesting LAN services e.g. where are you?
5) Internet radio
6) and many others...

On unix you can type grep udp /etc/services to get a list of UDP protocols implemented
today... there are hundreds.

泪是无色的血 2024-08-02 00:17:44

请参阅 Steven 的 Unix 网络编程 的第 22.4 节,“何时使用 UDP 而不是 TCP”。

另外,请参阅有关 UDP 的误解的其他 SO 答案总是比 TCP 更快

Steven 的说法可以总结如下:

  • 使用 UDP 进行广播和多播,因为这是您唯一的选择(对任何新应用程序使用多播)
  • 您可以将 UDP 用于简单的请求/回复应用程序,但您需要在自己的应用程序中构建自己的确认、超时和重传
  • 不要使用 UDP 进行批量数据传输。

Look at section 22.4 of Steven's Unix Network Programming, "When to Use UDP Instead of TCP".

Also, see this other SO answer about the misconception that UDP is always faster than TCP.

What Steven's says can be summed up as follows:

  • Use UDP for broadcast and multicast since that is your only option ( use multicast for any new apps )
  • You can use UDP for simple request / reply apps, but you'll need to build in your own acks, timeouts and retransmissions
  • Don't use UDP for bulk data transfer.
偏爱你一生 2024-08-02 00:17:44

我们知道UDP是一种无连接的协议,因此它

  1. 适合于需要简单的请求-响应通信的过程。
  2. 适用于有内部流量的进程,错误控制
  3. 适用于广播和组播

具体示例:

  • 用于 SNMP
  • 用于一些路由更新协议,如 RIP

We know that the UDP is a connection-less protocol, so it is

  1. suitable for process that require simple request-response communication.
  2. suitable for process which has internal flow ,error control
  3. suitable for broad casting and multicasting

Specific examples:

  • used in SNMP
  • used for some route updating protocols such as RIP
纵性 2024-08-02 00:17:44

与 TCP 和 UDP 相比,UDP 等无连接协议保证了速度,但不能保证数据包传输的可靠性。
例如,在视频游戏中通常不需要可靠的网络,但速度是最重要的,使用 UDP 进行游戏具有减少网络延迟的优点。

输入图片此处描述

Comparing TCP with UDP, connection-less protocols like UDP assure speed, but not reliability of packet transmission.
For example in video games typically don't need a reliable network but the speed is the most important and using UDP for games has the advantage of reducing network delay.

enter image description here

無心 2024-08-02 00:17:44

如果沿途丢失一些数据不会完全破坏正在传输的数据,则您希望使用基于 TCP 的 UDP。 它的很多用途是在实时应用程序中,例如游戏(即 FPS),您不必总是知道每个玩家在任何给定时间的位置,如果您一路上丢失了一些数据包,新的数据将正确地告诉您玩家在哪里),以及实时视频流(一个损坏的帧不会破坏观看体验)。

You want to use UDP over TCP in the cases where losing some of the data along the way will not completely ruin the data being transmitted. A lot of its uses are in real-time applications, such as gaming (i.e., FPS, where you don't always have to know where every player is at any given time, and if you lose a few packets along the way, new data will correctly tell you where the players are anyway), and real-time video streaming (one corrupt frame isn't going to ruin the viewing experience).

牛↙奶布丁 2024-08-02 00:17:44

我们的 Web 服务在尽可能多的 PC 上拥有数千个 winforms 客户端。 PC 与数据库后端没有连接,所有访问均通过 Web 服务进行。 因此,我们决定开发一个中央日志服务器,它侦听 UDP 端口,所有客户端都会发送一个 xml 错误日志数据包(使用 log4net UDP 附加程序),该数据包在收到后转储到数据库表中。 因为我们并不真正关心是否遗漏了一些错误日志,并且有数千个客户端,所以使用专用日志服务而不加载主 Web 服务会很快。

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.

以为你会在 2024-08-02 00:17:44

当 TCP 可能工作时,我有点不愿意建议 UDP。 问题是,如果 TCP 由于某种原因无法工作(因为连接太滞后或拥塞),则将应用程序更改为使用 UDP 不太可能有帮助。 糟糕的连接对 UDP 来说也是有害的。 TCP 在最小化拥塞方面已经做得非常好。

我能想到的唯一需要 UDP 的情况是广播协议。 在应用程序涉及两个已知主机的情况下,UDP 可能只会提供边际性能优势,但会大幅增加代码复杂性的成本。

I'm a bit reluctant to suggest UDP when TCP could possibly work. The problem is that if TCP isn't working for some reason, because the connection is too laggy or congested, changing the application to use UDP is unlikely to help. A bad connection is bad for UDP too. TCP already does a very good job of minimizing congestion.

The only case I can think of where UDP is required is for broadcast protocols. In cases where an application involves two, known hosts, UDP will likely only offer marginal performance benefits for substantially increased costs of code complexity.

美男兮 2024-08-02 00:17:44

仅当您确实知道自己在做什么时才使用 UDP。 如今,UDP 的情况极为罕见,但尝试在任何地方坚持使用 UDP 的专家(甚至是非常有经验的)专家的数量似乎不成比例。 也许他们喜欢自己实现错误处理和连接维护代码。

由于所谓的校验和印记,现代网络接口卡的 TCP 预计会更快。 令人惊讶的是,在快速连接速度(例如 1Gbps)下,计算校验和对于 CPU 来说将是一个很大的负载,因此它被卸载到 NIC 硬件来识别 TCP 数据包进行印记,并且它不会为您提供相同的服务。

Only use UDP if you really know what you are doing. UDP is in extremely rare cases today, but the number of (even very experienced) experts who would try to stick it everywhere seems to be out of proportion. Perhaps they enjoy implementing error-handling and connection maintenance code themselves.

TCP should be expected to be much faster with modern network interface cards due to what's known as checksum imprint. Surprisingly, at fast connection speeds (such as 1Gbps) computing a checksum would be a big load for a CPU so it is offloaded to NIC hardware that recognizes TCP packets for imprint, and it won't offer you the same service.

离线来电— 2024-08-02 00:17:44

UDP 非常适合 VoIP 寻址,无论其可靠性如何,都必须发送数据包......
视频聊天是UDP的一个例子(您可以在任何视频聊天期间通过wireshark网络捕获来检查它)。
此外,TCP 不适用于 DNS 和 SNMP 协议。
UDP没有任何开销,而TCP有大量开销

UDP is perfect for VoIP addressed where data packet has to be sent regard less its reliability...
Video chatting is an example of UDP (you can check it by wireshark network capture during any video chatting)..
Also TCP doesn't work with DNS and SNMP protocols.
UDP does not have any overhead while TCP have lots of Overhead

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

在您确实想快速向另一台服务器获得简单答案的情况下,UDP 效果最好。 一般来说,您希望答案位于一个响应数据包中,并且您准备实施自己的协议以提高可靠性或重新发送。 DNS 是这个用例的完美描述。 连接设置的成本太高(然而,DNS
也支持 TCP 模式)。

另一种情况是,当您交付可能丢失的数据时,因为传入的新数据将替换以前的数据/状态。 我会想到天气数据、视频流、股票报价服务(不用于实际交易)或游戏数据。

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

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

This is one of my favorite questions. UDP is so misunderstood.

In situations where you really want to get a simple answer to another server quickly, UDP works best. In general, you want the answer to be in one response packet, and you are prepared to implement your own protocol for reliability or to resend. DNS is the perfect description of this use case. The costs of connection setups are way too high (yet, DNS
does support a TCP mode as well).

Another case is when you are delivering data that can be lost because newer data coming in will replace that previous data/state. Weather data, video streaming, a stock quotation service (not used for actual trading), or gaming data comes to mind.

Another case is when you are managing a tremendous amount of state and you want to avoid using TCP because the OS cannot handle that many sessions. This is a rare case today. In fact, there are now user-land TCP stacks that can be used so that the application writer may have finer grained control over the resources needed for that TCP state. Prior to 2003, UDP was really the only game in town.

One other case is for multicast traffic. UDP can be multicasted to multiple hosts whereas TCP cannot do this at all.

无风消散 2024-08-02 00:17:43

如果 TCP 数据包丢失,则会重新发送。 对于依赖于以特定顺序实时处理数据的应用程序来说,这并不方便。

示例包括视频流,尤其是 VoIP(例如 Skype)。 然而,在这些情况下,丢包并不是什么大问题:我们的感官并不完美,所以我们甚至可能没有注意到。 这就是为什么这些类型的应用程序使用 UDP 而不是 TCP。

If a TCP packet is lost, it will be resent. That is not handy for applications that rely on data being handled in a specific order in real time.

Examples include video streaming and especially VoIP (e.g. Skype). In those instances, however, a dropped packet is not such a big deal: our senses aren't perfect, so we may not even notice. That is why these types of applications use UDP instead of TCP.

旧伤慢歌 2024-08-02 00:17:43

UDP的“不可靠”是一种形式主义。 不能绝对保证传输。 实际上,他们几乎总能成功。 他们只是没有被确认并在超时后重试。

协商 TCP 套接字和握手 TCP 数据包的开销是巨大的。 真的很大。 没有明显的 UDP 开销。

最重要的是,您可以轻松地通过一些比 TCP 开销更少的可靠传递握手来补充 UDP。 阅读此内容:http://en.wikipedia.org/wiki/Reliable_User_Datagram_Protocol

UDP 对于广播很有用发布-订阅类型的应用程序中的信息。 IIRC、TIBCO 大量使用 UDP 来通知状态更改。

任何其他类型的单向“重大事件”或“记录”活动都可以使用 UDP 数据包很好地处理。 您希望在不构建整个套接字的情况下发送通知。 您不期望来自各个听众的任何回应。

系统“心跳”或“我还活着”消息也是不错的选择。 失踪并不是一场危机。 (连续)缺少六个。

The "unreliability" of UDP is a formalism. Transmission isn't absolutely guaranteed. As a practical matter, they almost always get through. They just aren't acknowledged and retried after a timeout.

The overhead in negotiating for a TCP socket and handshaking the TCP packets is huge. Really huge. There is no appreciable UDP overhead.

Most importantly, you can easily supplement UDP with some reliable delivery hand-shaking that's less overhead than TCP. Read this: http://en.wikipedia.org/wiki/Reliable_User_Datagram_Protocol

UDP is useful for broadcasting information in a publish-subscribe kind of application. IIRC, TIBCO makes heavy use of UDP for notification of state change.

Any other kind of one-way "significant event" or "logging" activity can be handled nicely with UDP packets. You want to send notification without constructing an entire socket. You don't expect any response from the various listeners.

System "heartbeat" or "I'm alive" messages are a good choice, also. Missing one isn't a crisis. Missing half a dozen (in a row) is.

好多鱼好多余 2024-08-02 00:17:43

我开发的产品支持客户端和服务器之间的 UDP (IP) 和 TCP/IP 通信。 它始于 15 年前的 IPX,并于 13 年前添加了 IP 支持。 我们在三四年前添加了 TCP/IP 支持。 大胆猜测:UDP 与 TCP 代码的比例可能约为 80/20。 该产品是数据库服务器,因此可靠性至关重要。 我们必须处理其他答案中已经提到的 UDP 带来的所有问题(数据包丢失、数据包加倍、数据包顺序等)。 很少有问题,但有时确实会发生,因此必须加以处理。 支持 UDP 的好处是我们能够根据自己的使用情况对其进行一些定制,并调整它的性能。

每个网络都会有所不同,但 UDP 通信协议通常对我们来说更快一点。 持怀疑态度的读者会正确地质疑我们是否正确实施了一切。 另外,你对一个拥有两位数名次的人还能指望什么呢? 尽管如此,出于好奇,我刚刚进行了测试。 测试读取100万条记录(select * from sometable)。 我将每个客户端请求返回的记录数设置为 1、10,然后是 100(每个协议运行 3 次测试)。 服务器距离 100Mbit LAN 仅两跳。 这些数字似乎与其他人过去发现的结果一致(UDP 在大多数情况下大约快 5%)。 此特定测试的总时间(以毫秒为单位)如下:

  1. 1 条记录
    • IP:390,760 毫秒
    • TCP:416,903 毫秒
  2. 10 条记录
    • IP:91,707 毫秒
    • TCP:95,662 毫秒
  3. 100 条记录
    • IP:29,664 毫秒
    • TCP:30,968 毫秒

IP 和 TCP 传输的总数据量大致相同。 我们在 UDP 通信方面有额外的开销,因为我们有一些与 TCP/IP“免费”获得的相同内容(校验和、序列号等)。 例如,Wireshark 显示下一组记录的请求在 UDP 中为 80 字节,在 TCP 中为 84 字节。

I work on a product that supports both UDP (IP) and TCP/IP communication between client and server. It started out with IPX over 15 years ago with IP support added 13 years ago. We added TCP/IP support 3 or 4 years ago. Wild guess coming up: The UDP to TCP code ratio is probably about 80/20. The product is a database server, so reliability is critical. We have to handle all of the issues imposed by UDP (packet loss, packet doubling, packet order, etc.) already mentioned in other answers. There are rarely any problems, but they do sometimes occur and so must be handled. The benefit to supporting UDP is that we are able to customize it a bit to our own usage and tweak a bit more performance out of it.

Every network is going to be different, but the UDP communication protocol is generally a little bit faster for us. The skeptical reader will rightly question whether we implemented everything correctly. Plus, what can you expect from a guy with a 2 digit rep? Nonetheless, I just now ran a test out of curiosity. The test read 1 million records (select * from sometable). I set the number of records to return with each individual client request to be 1, 10, and then 100 (three test runs with each protocol). The server was only two hops away over a 100Mbit LAN. The numbers seemed to agree with what others have found in the past (UDP is about 5% faster in most situations). The total times in milliseconds were as follows for this particular test:

  1. 1 record
    • IP: 390,760 ms
    • TCP: 416,903 ms
  2. 10 records
    • IP: 91,707 ms
    • TCP: 95,662 ms
  3. 100 records
    • IP: 29,664 ms
    • TCP: 30,968 ms

The total data amount transmitted was about the same for both IP and TCP. We have extra overhead with the UDP communications because we have some of the same stuff that you get for "free" with TCP/IP (checksums, sequence numbers, etc.). For example, Wireshark showed that a request for the next set of records was 80 bytes with UDP and 84 bytes with TCP.

浪菊怪哟 2024-08-02 00:17:43

这里已经有很多很好的答案,但我想添加一个非常的因素以及总结。 UDP 通过正确的调整可以实现更高的吞吐量,因为它不采用拥塞控制。 TCP 中的拥塞控制非常非常非常重要。 它控制连接的速率和吞吐量,以便通过尝试估计连接的当前容量来最大限度地减少网络拥塞。 即使数据包通过非常可靠的链路(例如在核心网络中)发送,路由器的缓冲区大小也有限。 这些缓冲区填满其容量,然后数据包被丢弃,TCP 通过缺少收到的确认来注意到这种丢弃,从而限制连接速度以估计容量。 TCP 还采用了称为“慢启动”的技术,但吞吐量(实际上是“拥塞窗口”)会缓慢增加,直到数据包被丢弃,然后降低并再次缓慢增加,直到数据包被丢弃。丢弃等。这会导致 TCP 吞吐量波动。 当您下载大文件时,您可以清楚地看到这一点。

因为 UDP 不使用拥塞控制,所以它可以更快并且延迟更小,因为它不会寻求最大化直到丢弃点的缓冲区,即 UDP 数据包在缓冲区中花费的时间更少,并且以更少的延迟更快地到达那里。 由于 UDP 不采用拥塞控制,而 TCP 却采用拥塞控制,因此它可能会夺走 TCP 的容量,从而让出 UDP 流。

不过,UDP 仍然容易受到拥塞和数据包丢失的影响,因此您的应用程序必须准备好以某种方式处理这些复杂情况,可能使用重传或纠错码。

结果是 UDP 可以:

  • 只要网络丢包率在应用程序可以处理的范围内,就能实现比 TCP 更高的吞吐量。
  • 传输数据包的速度比 TCP 更快且延迟更小。
  • 建立连接速度更快,因为无需初始握手即可建立连接
  • 传输多播数据包,而 TCP 必须使用多个连接。
  • 传输固定大小的数据包,而 TCP 则分段传输数据。 如果您传输 300 字节的 UDP 数据包,您将在另一端收到 300 字节。 使用 TCP,您可以向发送套接字提供 300 个字节,但接收方只能读取 100 个字节,并且您必须以某种方式弄清楚还有 200 个字节在路上。 如果您的应用程序传输固定大小的消息而不是字节流,这一点很重要。

总之,UDP 可以用于 TCP 可以使用的所有类型的应用程序,只要您还实现适当的重传机制。 UDP 速度非常快,延迟较小,不受连接拥塞的影响,传输固定大小的数据报,并且可用于多播。

There are already many good answers here, but I would like to add one very important factor as well as a summary. UDP can achieve a much higher throughput with the correct tuning because it does not employ congestion control. Congestion control in TCP is very very important. It controls the rate and throughput of the connection in order to minimize network congestion by trying to estimate the current capacity of the connection. Even when packets are sent over very reliable links, such as in the core network, routers have limited size buffers. These buffers fill up to their capacity and packets are then dropped, and TCP notices this drop through the lack of a received acknowledgement, thereby throttling the speed of the connection to the estimation of the capacity. TCP also employs something called slow start, but the throughput (actually the congestion window) is slowly increased until packets are dropped, and is then lowered and slowly increased again until packets are dropped etc. This causes the TCP throughput to fluctuate. You can see this clearly when you download a large file.

Because UDP is not using congestion control it can be both faster and experience less delay because it will not seek to maximize the buffers up to the dropping point, i.e. UDP packets are spending less time in buffers and get there faster with less delay. Because UDP does not employ congestion control, but TCP does, it can take away capacity from TCP that yields to UDP flows.

UDP is still vulnerable to congestion and packet drops though, so your application has to be prepared to handle these complications somehow, likely using retransmission or error correcting codes.

The result is that UDP can:

  • Achieve higher throughput than TCP as long as the network drop rate is within limits that the application can handle.
  • Deliver packets faster than TCP with less delay.
  • Setup connections faster as there are no initial handshake to setup the connection
  • Transmit multicast packets, whereas TCP have to use multiple connections.
  • Transmit fixed size packets, whereas TCP transmit data in segments. If you transfer a UDP packet of 300 Bytes, you will receive 300 Bytes at the other end. With TCP, you may feed the sending socket 300 Bytes, but the receiver only reads 100 Bytes, and you have to figure out somehow that there are 200 more Bytes on the way. This is important if your application transmit fixed size messages, rather than a stream of bytes.

In summary, UDP can be used for every type of application that TCP can, as long as you also implement a proper retransmission mechanism. UDP can be very fast, has less delay, is not affected by congestion on a connection basis, transmits fixed sized datagrams, and can be used for multicasting.

浅浅淡淡 2024-08-02 00:17:43

UDP 是一种无连接协议,用于 SNMPDNS,其中无序到达的数据包是可以接受的,并且数据包的立即传输很重要。

它在 SNMP 中使用,因为网络管理通常必须在网络处于压力下时进行,即难以实现可靠、拥塞控制的数据传输时。

它用在DNS中,因为它不涉及连接建立,从而避免连接建立延迟。

干杯

UDP is a connection-less protocol and is used in protocols like SNMP and DNS in which data packets arriving out of order is acceptable and immediate transmission of the data packet matters.

It is used in SNMP since network management must often be done when the network is in stress i.e. when reliable, congestion-controlled data transfer is difficult to achieve.

It is used in DNS since it does not involve connection establishment, thereby avoiding connection establishment delays.

cheers

乖乖兔^ω^ 2024-08-02 00:17:43

UDP 确实具有较少的开销,并且适合执行诸如流式传输音频或视频等实时数据之类的操作,或者在数据丢失也没关系的任何情况下。

UDP does have less overhead and is good for doing things like streaming real time data like audio or video, or in any case where it is ok if data is lost.

迷路的信 2024-08-02 00:17:43

据我所知,这个问题的最佳答案之一来自Hacker News 的用户 zAy0LfpBZLC8mAC。 这个答案太好了,我只是按原样引用它。

TCP 具有队头阻塞,因为它保证完整且有序
交付,因此当数据包在传输过程中丢失时,它必须等待
重传丢失的数据包,而 UDP 将数据包传送到
申请书到达时,包括重复的且没有任何
保证数据包完全到达或按什么顺序到达(它
实际上本质上是带有端口号和(可选)有效负载的 IP
添加了校验和),但这对于电话来说很好,例如,它
当几毫秒的音频被播放时,通常根本不重要
失踪了,但是延迟很烦人,所以你不用理会
重新传输,您只需删除所有重复项,将重新排序的数据包排序到
几百毫秒抖动缓冲区的正确顺序,以及
如果数据包没有及时出现或根本没有出现,它们就会被跳过,
在编解码器支持的情况下可能进行插值。

此外,TCP 的一个主要部分是流量控制,以确保您得到
尽可能多的吞吐量,但不会使网络超载(
有点多余,因为过载的网络会丢弃你的数据包,
这意味着您必须重新传输,这会损害吞吐量),UDP
没有任何这些 - 这对于像这样的应用程序是有意义的
电话,因为具有给定编解码器的电话需要一定数量的
带宽,你不能“放慢速度”,并且额外的带宽也
不会使通话速度更快。

除了实时/低延迟应用程序之外,UDP 还适用于
非常小的事务,例如 DNS 查找,只是因为它
没有 TCP 连接建立和拆除开销,
无论是在延迟方面还是在带宽使用方面。 如果你的
请求小于典型的 MTU,响应可能是,
同样,您可以在一次往返中完成,无需保留任何状态
在服务器上,流量控制和排序以及所有可能的事情
对于此类用途也不是特别有用。

然后,您可以使用 UDP 构建您自己的 TCP 替代品,例如
当然,但是如果没有深入的了解,这可能不是一个好主意
了解网络动态,现代 TCP 算法很漂亮
复杂。

另外,我想应该提到的是,不仅仅是 UDP 和
TCP,例如SCTP、DCCP。 目前唯一的问题是
(IPv4) 互联网充满了 NAT 网关,这使得无法
在最终用户应用程序中使用 UDP 和 TCP 以外的协议。

One of the best answer I know of for this question comes from user zAy0LfpBZLC8mAC at Hacker News. This answer is so good I'm just going to quote it as-is.

TCP has head-of-queue blocking, as it guarantees complete and in-order
delivery, so when a packet gets lost in transit, it has to wait for a
retransmit of the missing packet, whereas UDP delivers packets to the
application as they arrive, including duplicates and without any
guarantee that a packet arrives at all or which order they arrive (it
really is essentially IP with port numbers and an (optional) payload
checksum added), but that is fine for telephony, for example, where it
usually simply doesn't matter when a few milliseconds of audio are
missing, but delay is very annoying, so you don't bother with
retransmits, you just drop any duplicates, sort reordered packets into
the right order for a few hundred milliseconds of jitter buffer, and
if packets don't show up in time or at all, they are simply skipped,
possible interpolated where supported by the codec.

Also, a major part of TCP is flow control, to make sure you get as
much througput as possible, but without overloading the network (which
is kinda redundant, as an overloaded network will drop your packets,
which means you'd have to do retransmits, which hurts throughput), UDP
doesn't have any of that - which makes sense for applications like
telephony, as telephony with a given codec needs a certain amount of
bandwidth, you can not "slow it down", and additional bandwidth also
doesn't make the call go faster.

In addition to realtime/low latency applications, UDP makes sense for
really small transactions, such as DNS lookups, simply because it
doesn't have the TCP connection establishment and teardown overhead,
both in terms of latency and in terms of bandwidth use. If your
request is smaller than a typical MTU and the repsonse probably is,
too, you can be done in one roundtrip, with no need to keep any state
at the server, and flow control als ordering and all that probably
isn't particularly useful for such uses either.

And then, you can use UDP to build your own TCP replacements, of
course, but it's probably not a good idea without some deep
understanding of network dynamics, modern TCP algorithms are pretty
sophisticated.

Also, I guess it should be mentioned that there is more than UDP and
TCP, such as SCTP and DCCP. The only problem currently is that the
(IPv4) internet is full of NAT gateways which make it impossible to
use protocols other than UDP and TCP in end-user applications.

陌路黄昏 2024-08-02 00:17:43

视频流是使用 UDP 的完美示例。

Video streaming is a perfect example of using UDP.

明媚如初 2024-08-02 00:17:43

UDP 的开销较低,正如已经提到的,它非常适合视频和音频等流媒体内容,最好只是丢失一个数据包,然后尝试重新发送并赶上。

TCP 传输没有任何保证,您只是应该被告知套接字是否已断开或者数据是否不会到达。 否则当它到达那里时它就会到达那里。

人们忘记的一件大事是,udp 是基于数据包的,而 tcp 是基于字节流的,不能保证您发送的“tcp 数据包”是显示在另一端的数据包,它可以被分解为尽可能多的数据包正如路由器和堆栈所希望的那样。 因此,您的软件具有将字节解析回可用数据块的额外开销,这可能需要相当大的开销。 UDP 可能会乱序,因此您必须对数据包进行编号,或者如果您愿意的话,可以使用其他机制对其进行重新排序。 但是,如果您收到该 udp 数据包,它会以与留下的顺序相同的所有相同字节到达,没有任何变化。 因此,术语“udp 数据包”有意义,但“tcp 数据包”则不一定。 TCP 有自己的重试和排序机制,该机制对您的应用程序是隐藏的,您可以使用 UDP 重新发明它,以根据您的需要进行定制。

UDP 在两端编写代码要容易得多,主要是因为您不必建立和维护点对点连接。 我的问题通常是在什么情况下您会需要 TCP 开销? 如果您采取捷径,例如假设收到的 TCP“数据包”是发送的完整数据包,您的情况会更好吗? (如果您费心检查长度/内容,您可能会扔掉两个数据包)

UDP has lower overhead, as stated already is good for streaming things like video and audio where it is better to just lose a packet then try to resend and catch up.

There are no guarantees on TCP delivery, you are simply supposed to be told if the socket disconnected or basically if the data is not going to arrive. Otherwise it gets there when it gets there.

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 is far easier to write code for on both ends, basically because you do not have to make and maintain the point to point connections. My question is typically where are the situations where you would want the TCP overhead? And if you take shortcuts like assuming a tcp "packet" received is the complete packet that was sent, are you better off? (you are likely to throw away two packets if you bother to check the length/content)

往日情怀 2024-08-02 00:17:43

视频游戏的网络通信几乎总是通过 UDP 完成。

速度至关重要,如果错过更新也并不重要,因为每次更新都包含玩家可以看到的完整当前状态。

Network communication for video games is almost always done over UDP.

Speed is of utmost importance and it doesn't really matter if updates are missed since each update contains the complete current state of what the player can see.

那一片橙海, 2024-08-02 00:17:43

关键问题与“在什么样的情况下 UDP 是更好的选择(相对于 tcp)”有关。

上面有很多很好的答案,但缺乏对传输不确定性对 TCP 性能影响的任何正式、客观的评估。

随着移动应用程序的大规模增长,以及随之而来的“偶尔连接”或“偶尔断开”范例,在某些情况下,当连接难以获得时,TCP 尝试维持连接的开销会导致强大的开销。 UDP 的案例及其“面向消息”的性质。

现在我没有这方面的数学/研究/数字,但我已经制作了一些应用程序,这些应用程序使用 ACK/NAK 和通过 UDP 的消息编号比在连接普遍较差和旧 TCP 较差时使用 TCP 更可靠地工作只是花费了我客户的时间和金钱来尝试建立联系。 在许多西方国家的地区和农村地区你都会遇到这种情况......

The key question was related to "what kind of situations would UDP be the better choice [over tcp]"

There are many great answers above but what is lacking is any formal, objective assessment of the impact of transport uncertainty upon TCP performance.

With the massive growth of mobile applications, and the "occasionally connected" or "occasionally disconnected" paradigms that go with them, there are certainly situations where the overhead of TCP's attempts to maintain a connection when connections are hard to come by leads to a strong case for UDP and its "message oriented" nature.

Now I don't have the math/research/numbers on this, but I have produced apps that have worked more reliably using and ACK/NAK and message numbering over UDP than could be achieved with TCP when connectivity was generally poor and poor old TCP just spent it's time and my client's money just trying to connect. You get this in regional and rural areas of many western countries....

小嗲 2024-08-02 00:17:43

在某些情况下,其他人已经强调了这一点,保证数据包的到达并不重要,因此使用 UDP 就可以了。 在其他情况下,UDP 优于 TCP。

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

In some cases, which others have highlighted, guaranteed arrival of packets isn't important, and hence using UDP is fine. There are other cases where UDP is preferable to TCP.

One unique case where you would want to use UDP instead of TCP is where you are tunneling TCP over another protocol (e.g. tunnels, virtual networks, etc.). If you tunnel TCP over TCP, the congestion controls of each will interfere with each other. Hence one generally prefers to tunnel TCP over UDP (or some other stateless protocol). See TechRepublic article: Understanding TCP Over TCP: Effects of TCP Tunneling on End-to-End Throughput and Latency.

当梦初醒 2024-08-02 00:17:43

当应用程序更关心“实时”数据而不是精确的数据复制时,可以使用 UDP。 例如,VOIP 可以使用 UDP,应用程序会担心数据包的重新排序,但最终 VOIP 并不需要每个数据包,但更重要的是需要许多数据包的连续流。 也许您遇到了语音质量的“故障”,但主要目的是您收到消息,而不是在另一端完美地重新创建消息。 UDP 还用于创建连接和与 TCP 同步的费用超过有效负载的情况。 DNS 查询就是一个完美的例子。 每个查询发出一个数据包,返回一个数据包。 如果使用 TCP,这将更加密集。 如果您没有收到 DNS 响应,只需重试即可。

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.

难理解 2024-08-02 00:17:43

当需要速度时使用 UDP,如果不需要数据包则使用准确性;当需要准确性时使用 TCP。

UDP 通常比较困难,因为您必须以不依赖于数据包准确性的方式编写程序。

UDP when speed is necessary and the accuracy if the packets is not, and TCP when you need accuracy.

UDP is often harder in that you must write your program in such a way that it is not dependent on the accuracy of the packets.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文