本文共 2699 字,大约阅读时间需要 8 分钟。
[Link]http://www.mindcontrol.org/~hplus/udp-vs-tcp.html
I've written an answer to the question "what's the difference between UDP and TCP" a few times now, so I figured I'd put it here.
With UDP, you send a packet (with a size) with sendto() from one side, and it'll be received using recvfrom() on the other side; each packet is distinct and has a length; it's not a stream like TCP is. UDP is "packet based". This is usually a plus.
With UDP, there is no GUARANTEE that the packet will make it, and you can't tell after calling sendto() whether it made it or not. However, 99% of all packets will make it. In practice, this is distributed such that usually, 100% of the packets make it, and 10% of the time, 90% of the packets make it. UDP is "unreliable". This is usually a minus.
With UDP there is no GUARANTEE that when sending packet A and then packet B to a client, the client will see first packet A and then packet B. It may see first B then A. Or not A at all. Or not B at all. Or neither. UDP is "unordered". This is usually a minus.
With UDP, there is no GURANTEE that you'll see the same packet only once. You may send A once, but you'll receive A twice, or three times (or zero times) on the other end. However, packet duplication is very uncommon. UDP is "not guaranteed unique". This is usually a minus.
With UDP, you can use the same socket/port to sendto() and recvfrom() any number of other machines, because the address to send to is specified each time you call sendto(). UDP is "connectionless". This is usually a plus.
With TCP, if you drop a packet, but the next packet makes it through, the kernel will withhold that packet until the earlier packet can be re-sent. This is because TCP is a guaranteed, in-order, stream protocol. This means that "fresh" data will sit in the kernel, becoming "stale," while you're waiting for the TCP time-out and re-transmit, which is a minimum of 3 seconds for a lost packet. This is why UDP is usually better for games, voice conferencing, and other low-latency applications. This is usually a (big) plus for UDP.
Additional:
1.在处理 UDP协议的时候,需要注意的是,UDP和TCP不一样。UDP没有control flow,如果接收端的buffer满掉了,再来的UDP包都会被drop掉。所以在处理UDP协议的时候,一般需要专门一个线程读UDP包,防止过多的数据包丢失。
2.最后,网络数据包多大合适? 这个很难说。对于UDP来说,小包是不划算的. 我们通常用的Ethernet(也就是LAN),在第2层Data link layer,最大的frame size 是1500 bytes,刨除最20 Bytes(最少)的IP头,8 bytes的UDP头,所有最大的UDP包可以包含 1472个bytes。要是考虑IP包有可能会有附加头信息,一般1400就比较合适。但是如果有些老版本router不地道,对你的UDP包分片的话,就比较惨了。能保证不分片的UDP包大小是513个byte左右 [5],不过毕竟现在这种老的Router很少了,1400字节大小的UDP包还是比较安全的。对于TCP来说,因为是stream protocol,不用考虑包的大小。但是TCP有个缺点,就是如果你一次发送很多很多数据,那么TCP的速度会一会快,一会慢(见[4]中的关于video streaming的介绍)。所以,需要程序调节,匀速发送数据。
[Ref link]http://data.gameres.com/document.asp?TopicID=66266
转载地址:http://udzvb.baihongyu.com/