什么时候适合使用 UDP 而不是 TCP? [英] When is it appropriate to use UDP instead of TCP?

查看:28
本文介绍了什么时候适合使用 UDP 而不是 TCP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Since TCP guarantees packet delivery and thus can be considered "reliable", whereas UDP doesn't guarantee anything and packets can be lost. What would be the advantage of transmitting data using UDP in an application rather than over a TCP stream? In what kind of situations would UDP be the better choice, and why?

我假设 UDP 更快,因为它没有创建和维护流的开销,但如果某些数据永远不会到达其目的地,那不是无关紧要吗?

I'm assuming that UDP is faster since it doesn't have the overhead of creating and maintaining a stream, but wouldn't that be irrelevant if some data never reaches its destination?

推荐答案

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

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

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

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.

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

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.

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

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

这篇关于什么时候适合使用 UDP 而不是 TCP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆