Reprint: http://blog.csdn.net/dog250/article/details/6896949
panorama Analysis of the problem of UDP protocol 2011-10-22 19:262989 People readComments (4)CollectionReportTCP Network algorithm traffic socket communication now, whenever said to be proficient in the network, the second meaning is "proficient in TCP", in fact, many people claiming to be proficient in TCP is only proficient in the socket interface, the TCP behavior is not proficient, the author is not proficient, but definitely more than the middle level. If you are really proficient in TCP behavior, then this article does not read, direct mail to me, we learn, if only to understand the socket interface, then the proposed text, and then must look at the "TCP protocol troubleshooting panoramic resolution"
0.UDP protocol and TCP protocol UDP is the abbreviation of User Datagram Protocol, for packet switching network, it actually plays the role of traditional post office, while TCP is playing the role of telephone operators and logistics companies, for packet switching networks, UDP is more basic than TCP, it can be said that TCP is the realization of a flow-based communication process, on the IP datagram Protocol, TCP and UDP respectively to achieve higher levels of "circuit switching" and "packet switching."
1. Connected UDP (connect UDP) Many people think that the UDP connection does not matter, but it is not so simple, whatever the technical thing, no matter, unless you can give you do not matter more than a reason.
1.1. Efficiency in the operation of the TCP/IP protocol, when it comes down to writing a network-based communication code, you must know where the protocol you are using is implemented, and for most operating systems, the protocol stack is part of the kernel, so they run in kernel space. This involves a problem that affects efficiency, which is the process of switching between kernel space and user space you need to understand that for x86 processors and most other processors, this switchover is time consuming and involves context save/restore, so if your application is efficiency-first, Then it is necessary to minimize the number of switching, which is not enough, and if the switch can not avoid, then try to reduce the number of copies, because UDP is based on the datagram, the data as long as ready to call a send or sendto, which is determined by the application logic, However, we can decide whether to use Send or sendto, to see the parameters, SendTo more parameters than send, so this means that if you use sendto, you need to copy more parameters, parameters into the kernel space, The kernel also prepares the data structure to hold these parameters temporarily, and when it is emitted, the kernel needs to release these temporarily stored parameters (which can, of course, be used to manage these parameters for automatic release).
If a UDP is connect, then you can directly call send after connect, the kernel in the application of connect after the permanent maintenance of the UDP connection, each time after sending and receiving data, the kernel no longer need to allocate/delete the data, but just find it, It also reduces the amount of data copied, since connect's UDP already has a "connection" in the kernel, so whenever the communication is not finished, the kernel can always trace the "connection" at any time, so it leads to 1.2.
1.2. Error message if it is a UDP with no "connection", the data will release any information about the destination after the call is made to sendto, but if the data is eventually encapsulated by IP (or is encapsulated by any underlying protocol with an error), Data on the halfway or end of the encounter some kind of problem can not reach the destination, there will be ICMP (for non-IP protocol, can be other mechanism) error information returned, but the sender is no longer likely to know the error message to which application (source/destination information has been released).
For UDP communication with "Connect", since the kernel stack has maintained a one-way connection from source to destination, when the error message is sent, the kernel stack will pinpoint exactly which application to forward to.
Finally, the UDP connection is unidirectional and does not generate any traffic when calling connect, it only binds a pair of five tuples in the kernel stack, the five tuple is: UDP protocol/source ip/source Port/Destination ip/destination port.
2.UDP High Efficiency Myth If you ask the difference between TCP and UDP online, the result is nothing more than the following: UDP does not need processing confirmation, UDP is more efficient, based on connection and no connection, TCP consumes resources, ...
But these are myths and myths that are meant to be broken. UDP is not necessarily more efficient than TCP, you know, TCP developed to today, its algorithm is very rich, reasonable configuration can be enough to cope with a variety of complex environment, in most cases will be more efficient than UDP.
3.UDP Design-multiplexing of IP is only a protocol family, in this protocol family, the completion of all the work should be done, UDP as a datagram protocol, its more role is to use the concept of port application reuse, in the implementation, it is basically replicating the IP protocol, On the basis of replication, an optional checksum is added to protect the integrity of the data to a certain extent, but you can also avoid it.
The IP protocol perfectly implements the datagram business, regardless of the result, the best effort-although ICMP provides a limited amount of feedback information. Some people say that IP protocol is not responsible, but the essence of layered model is that each layer only provide a single service, which is the philosophy of UNIX. The IP protocol only provides the lowest level datagram packet switching communication, which is a communication model that is completely parallel to the circuit exchange. Sometimes, really need such "after hair regardless, best effort" Service, TCP/IP is a wonderful solution is not directly let IP to provide this service, but on the IP to provide multiplexing UDP, the result is, for the host, the same IP can host a number of "after the hair regardless, best effort" service, IP ultimately only provides transport services.
4.UDP of the use of the prelude to read the 3rd section, then we will then say, in the end what business needs "after the hair, do the best" service? In reality, we know that the ordinary mail is such a business, speaking of ordinary mail, it is worth to read, and almost no longer need to write a letter, when I went to college, a week to the distant girlfriend sent at least one letter, but sometimes the letter arrived within a week, but sometimes, the letter was lost, So I have to spend a lot of time and money to explain to prove that I really wrote the letter, but did not send it, and sometimes, when I explained, the letter arrived, delayed for a long time. This is after the hair no matter, the best effort service, there is a time, in order to clarify a fact-this letter must not be lost, I used the speedpost, although did not show what express, but I received a receipt, this is not after the delivery of services, but "with the confirmation of the service", Therefore, it is necessary to clarify whether there is no inevitable correlation between post-mailing and communication efficiency.
Many people think that UDP applications in the real-time requirements of high-level areas, and then say what their own completion sequence and retransmission, since the need for order and retransmission, then why not directly use TCP, these people actually know that TCP is inefficient because it needs to deal with the sequential delivery and processing retransmission. If you add these features to UDP, will it not be the advantage of UDP?
I think, these people must be textbooks read too much, plus all kinds of textbooks are from so many classic books and a few RFCs excerpt, so "the world textbooks a big copy" itself has achieved zhongkoushuojin effect. The reality is far from simple. Does TCP really have a high efficiency of UDP? Not necessarily!
To know, we netizens live in the Internet every communication pipeline is not a fixed capacity, but can be scaled, but the standard UDP is sent with a fixed length per packet, for the sake of simplicity, using the UDP protocol between the application of the use of fixed-size packet communication, there is a problem ...
4.1. Problem one: Can not take advantage of idle bandwidth caused by a simple scenario of resource waste, UDP each with a 512-byte fixed-length packet communication, which means that the sender sends 512 bytes, the receiver receives 512 bytes, each 512 bytes encapsulation of an IP packet, in addition to port reuse this advantage, The package cost of a UDP header is added in vain. Even if you can send more data at once, and every 512 bytes, for applications that use TCP, data arrives at the kernel stack, and in some cases it can be saved for a while, saving the cost of encapsulation, but not wasting time causing interaction problems, because TCP uses a clever algorithm, When the discovery of data must be accumulated, it is not at this time to accumulate or not, TCP's complex algorithm will be a good balance between latency and throughput, see "The TCP protocol troubleshooting panoramic resolution"
The simplest fact is that the MTU of the link will hardly affect the UDP, which affects TCP, which directly affects the IP shard, which is an efficiency issue, at the extreme point, UDP may be sent each packet is a few 1% of the MTU, it may be hundreds of times times the MTU, the former is too inefficient, The latter will consume the transfer to marry the IP.
4.2. Problem two: Network congestion or performance mismatch can not be feedback resulting in a large number of packet loss for TCP, it could use congestion control and flow control algorithm to intelligently control the transmission rate, and for UDP, because there is no confirmation mechanism, even if the network congestion or the end of the machine is too much, the sending end is still sending , this will aggravate the pathological deterioration degree, for this deterioration, UDP send and receive both ends need not take any responsibility, see 5.1.
4.3. Improved UDP package for dynamic length cost too high due to the above two problems, it is necessary to make some adjustments to UDP in the user state, however, because of the existence of TCP, whether it is to do the adjustment or direct use of TCP, this is a problem, the final solution of the problem involves the time cost and the cost of money.
5.UDP Real Use occasions 5.1. Network situation in fairness Although UDP does not have traffic control and congestion control, and does not need to be confirmed, but this does not necessarily improve efficiency, as the saying goes, ax, sometimes some necessary maintenance work is to do, although UDP is much simpler than TCP, But in this concise behind, its high efficiency of the illusion will inevitably have some deceiving means, a UDP datagram sent to no matter, you do not receive confirmation, so you default it has reached the end of the security, it is like you do not want the code error, so you will be the code in the error prompt deletion is the same reason.
In fact, in the case of extreme network congestion, UDP packet loss rate is extremely high, this is because it does not have congestion control, because there is no traffic control, at both ends of the rate mismatch, there will be persistent high packet loss rate, and TCP does not have this problem, because it will self-tuning.
Again on the impact of fairness. TCP is inherently fair, and UDP is not, it's completely out of order, just like the definition of a real packet switching network. Because of the lack of order, the network situation will not feed back to the endpoint, not only itself will cause high packet loss rate, but also squeeze the bandwidth of TCP traffic.
End this section with an example, that is, road traffic. Beijing traffic can be regarded as UDP, and Shanghai traffic is TCP, although all face congestion, but you will find that once the Beijing car encounter congestion, almost die, and Shanghai, although some roads than Beijing is still blocked, but will not be stuck, traffic, even if slow will still slow forward.
5.2. Communication continuity and interactivity for packet-switched network communication, the cost of the protocol stack is mainly shown in the following aspects: A. Space complexity caused by encapsulation; B. The time complexity caused by the cache. For encapsulation, no doubt and the cache is directly opposite, if you want to send the data immediately, then you need to directly encapsulated and sent to the lower layer, which undoubtedly consumes more protocol head space, if you do not want to consume, then the load cache, when the cache reaches a certain amount of time to send, so "protocol head/load" The value will be minimized, undoubtedly saving space, but wasting time.
After understanding the above principles, then you may think of two types of communication, one is short-link communication, one is long-connected communication. Consider the communication efficiency when it is necessary to consider the impact of the continuity of communication, if you only need to send a package and the package can be sent regardless of and have a re-send/polling mechanism, then UDP is better, if at this time with TCP, the light handshake needs 2 packets (the third handshake can carry data), the average is not cost-effective, Such an example is a DNS query. Conversely, if a long connection, the TCP handshake and wave of extra time will be divided into long-lasting communication, in the persistent communication, the application can get additional benefits from the TCP stream, such as the accumulation of transmission, the benefits of the Nagel algorithm and so on, in addition, in most cases, confirmation is not a cost, Because many TCP algorithms are either a piggyback acknowledgement or a delay acknowledgement, in most cases, the acknowledgement packet does not affect the sending side's rate and does not occupy the bandwidth.
In the user's interactive experience, the communication of the UDP protocol depends entirely on the sending and receiving of the application itself, but the communication of the TCP protocol is affected by the protocol stack, and the data emitted by the application is not necessarily the same as the network, for example, the Nagel algorithm will affect the actual transmission.
5.3. Communication behavior do you really want the data to be sent out? If not, then use TCP, do not make your own confirmation and connection, of course, in the case of short connections, you have to carefully weigh the TCP handshake overhead and your own implementation of the cost of confirmation.
Take DNS as an example, this is obviously not a post-application, but the DNS client can not receive a reply after a certain time, and then issue another query, which does not affect the final result, this is just an infrastructure type of single-point query task, not the computer before the final task of the user, so the use of UDP is completely possible, However, for HTTP is not the same, HTTP is essentially like a content transfer, and then the browser to parse the content and give the display, which has strict requirements for the format, and do not know the size of the results, the results of the format is not fixed, so a slight error will affect the browser parsing. One HTTP communication is not a pair of application communication, but involves a lot of other applications, such as server-side CGI and client script, so absolutely need to accurately transfer, at this time can not use UDP, even the short connection is to use TCP.
5.4. Multipoint communication we know that TCP is a connected communication protocol, before the actual transmission, you have to establish a two-way connection with the communication destination, and can only connect with the only destination, then if we want to pass the data to multiple destinations, then we need to establish a number of such connections, On top of TCP, it is not easy to implement multipoint communication, which is determined by the handshake protocol of TCP and the Wave protocol.
For UDP, because there is no connection, it is good to achieve multipoint communication, for the use of connected UDP, can use Dnat or load balancing technology to achieve multipoint communication. Since the UDP protocol does not need to establish a connection, it is possible to send data to a multicast address or to continuously send the same data to multiple destinations.
5.5. The data boundary UDP is based on the datagram, which means that each UDP packet has a boundary, which is the most different from the flow of communication, for TCP, exactly according to the data itself to define the boundary, and for UDP, it is completely in accordance with the actual content of each communication between the sending and receiving parties to define the boundary.
5.6. The fact that already exists we are in two well-known open source code will encounter the function of TCP with UDP, they are OpenSSL and OpenVPN, for OPENSSL,DTLS is completely for UDP-based applications to provide security protection, since it is called Transport Layer Security, That must be inclusive of the entire transport layer (in fact, the SSL protocol in a hierarchical sense with the TCP/IP transport layer does not have a relationship), for OpenVPN, is the historical reason to realize their own confirmation and retransmission, then there is no dtls can learn from, this is helpless. Therefore, we should not easily take these two events as a reference to the facts, in reference to a matter, must consider its historical background, reading history makes people wise, the fact is that.
5.7. Conclusion Therefore, it is advisable to use UDP only when you confirm the following facts
5.7.1. Your application is completely UDP complete, or you do not care about TCP will be affected 5.7.2. You are familiar with the network status, make sure that there is no mob stream behavior in the UDP network, and grab the bandwidth 5.7.3. Both sides of the communication configuration, load matching or manually solve these problems 5.7.4. Data facts prove that TCP is actually less efficient than UDP or that you are religiously obsessed with UDP's high-efficiency 5.7.5. You don't care about the 4 points above, or you don't understand. Network 5.7.6.TCP is not convenient to achieve multi-point transmission situation