In the application process of UDP protocol, we found the advantages of UDP socket to facilitate access to servers and clients. So what is UDP socket? Now let's give a brief introduction.
UDP socket
UDP provides an end-to-end service different from the TCP protocol. In fact, UDP only implements two functions:
1) add another layer of IP address and port based on the IP protocol)
2) The system detects possible data errors during data transmission and discards damaged data.
Due to its simplicity, UDP socket has some characteristics different from the TCP socket we have seen before.
For example, UDP sockets do not need to be connected before use. The TCP protocol is similar to the telephone communication, while the UDP protocol is similar to the mail communication: you do not need to "Connect" when sending a package or letter, but you have to specify a destination address for each package and letter. Similarly, each piece of information is a data packet, which loads its own address information and is independent from other information. When receiving information, UDP socket plays a role like a mailbox. All emails and packages sent from different addresses can be placed in it. Once created, UDP socket can be used to send messages continuously to different addresses or receive messages from any address.
Another difference between a UDP socket and a TCP socket is that they handle different information boundaries: a udp socket retains the border information. This feature makes it easier for applications to accept information in some ways than to use TCP sockets.
The last difference is that the end-to-end transmission service provided by UDP is best-effort, that is, UDP socket will transmit information as much as possible, however, there is no guarantee that the information will arrive at the destination address successfully, and the order of arrival of the information is not necessarily the same as the order in which it is sent, just as it is sent through the postal department ). Therefore, a program using UDP socket must be prepared to process information loss and rescheduling. We will give an example later)
Since UDP brings this extra burden to the program, why do we still use it instead of using the TCP protocol?
One of the reasons is efficiency: if an application only exchanges a small amount of data, such as a simple request message from the client to the server, or a response message in the opposite direction, the establishment of a TCP connection requires at least two times the amount of information and two times the round-trip delay time ).
Another reason is flexibility: if there are other requirements in addition to reliable byte stream services, UDP provides a platform with minimum overhead to meet any needs.
Java programmers use UDP sockets through the DatagramPacket class and the DatagramSocket class. Both the client and the server use mongoramsockets to send data and use mongorampackets to receive data.