When your talent is not enough to satisfy your ambition, you should settle down and study hard

Overview of UDP

  • UDP is the User Datagram Protocol. It is a connectionless transport layer Protocol in the Open System Interconnection (OSI) reference model. IETF RFC 768, which provides a transaction-oriented simple unreliable message delivery service, is the official specification for UDP. The protocol number of UDP IP packets is 17.

  • UDP is a connectionless protocol used to process data packets like TCP on the network. In the OSI model, layer 4, the transport layer, is one layer above the IP protocol. UDP does not provide packet grouping, assembly, and sorting. That is, after a packet is sent, it is impossible to know whether the packet arrived safely and intact. UDP is used to support network applications that need to transfer data between computers. Many client/server network applications, including network video conference system, need to use UDP protocol. UDP protocol has been used for many years since its appearance, although its initial luster has been overshadowed by some similar protocols, but even today UDP is still a very practical and feasible network transport layer protocol.

Main features of UDP

  • UDP is a connectionless protocol that transfers data without establishing a connection between the source and the terminal. When it wants to transfer data, it simply grabs the data from the application and throws it on the network as quickly as possible. On the sending side, the speed at which UDP can transmit data is limited only by the speed at which the application can generate the data, the power of the computer, and the transmission bandwidth; At the receiving end, UDP queues each message segment, and the application reads one message segment at a time from the queue.

  • Since no connection is established for data transmission, there is no need to maintain connection state, including sending and receiving state, so a single server machine can simultaneously transmit the same message to multiple clients.

  • The header of a UDP packet is short, only 8 bytes, and the additional overhead of UDP is small compared to TCP’s 20 bytes packet.

  • Throughput is not regulated by the congestion control algorithm, but is limited only by the rate of data generated by the application software, transmission bandwidth, and the performance of the source and terminal hosts.

  • UDP is packet oriented. The UDP packets sent by the sender to the application are forwarded to the IP layer after the header is added. Instead of splitting or merging, the boundaries of these messages are preserved, so the application needs to select the appropriate message size.

Although UDP is an unreliable protocol, it is an ideal one for distributing information. For example, reporting the stock market on the screen, showing airline information, and so on. UDP is also used to modify the Routing table in Routing Information Protocol (RIP). In these applications, if a message is lost, a new message will replace it a few seconds later. UDP is widely used in multimedia applications.

TCP is different from UDP

  • TCP is a connection-oriented transmission control protocol, while UDP provides connectionless datagram service.
  • TCP has high reliability, to ensure the correctness of data transmission, not missing or out-of-order, while UDP don’t establish a connection before transmitting data, incorrect data check and modification, do not need to wait for the reply of the other party, so there will be a packet loss, repetition, out-of-order, applications need to be responsible for all transmission reliability;
  • UDP has better real-time performance and higher work efficiency than TCP.
  • UDP segment structure is simpler than TCP segment structure, so the network overhead is lower.
  • TCP protocol can ensure that the receiver receives the byte stream sent by the sender without error, providing reliable communication service for the application program. Communication systems with high reliability requirements often use TCP to transmit data.

The main application

Applicable occasions

Caution must be exercised when selecting UDP as the transport protocol. When the network quality is not satisfactory, the LOSS of UDP packets is serious. However, because UDP is not a connection protocol, it has the advantages of low resource consumption and high processing speed. Therefore, UDP is often used in the transmission of audio, video, and ordinary data. Even if they occasionally lose one or two packets, they will not have a great impact on the received results. For example, ICQ and QQ that we chat with are UDP protocols.

The practical application

In the field of field measurement and control, for the distributed controller, monitor, etc., its application environment is relatively bad, so it puts forward different requirements for transmission data, such as real-time, anti-interference, security, etc. Based on this, in field communication, if an application wants to transmit a group of data to another node in the network, the UDP process can add the data header and then send to the IP process, UDP protocol eliminates the process of establishing and disconnecting the connection, cancels the retransmission check mechanism, and can achieve a higher communication rate.

Code demo

A simple client/server data sending and receiving example

UDP client:

public class UdpClient {

    public static void main(String[] args) throws IOException {
        // Create a socket
        DatagramSocket socket = new DatagramSocket();
        // Create a packet
        String msg = "Hello, server ~";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        // Send the packet
        socket.send(packet);
        / / close the flowsocket.close(); }}Copy the code

UDP server:

public class UdpServer {

    public static void main(String[] args) throws IOException {
        // Enable the port
        DatagramSocket socket = new DatagramSocket(9090);
        // Receive packets
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        // block reception
        socket.receive(packet);
        String msg = new String(packet.getData(),0,packet.getLength());
        System.out.println("Received data from client:" + msg);
        // Close the data streamsocket.close(); }}Copy the code

Simulate a conversation between a student and a teacher

/ / the client
public class TalkSend implements Runnable {

    DatagramSocket socket = null;
    
    BufferedReader br = null;

    private int formPort;
    
    private String toIp;
    
    private int toPort;

    public TalkSend(int formPort, String toIp, int toPort) {
        this.formPort = formPort;
        this.toIp = toIp;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(this.formPort);
            // Prepare the data console to read system.in
            br = new BufferedReader(new InputStreamReader(System.in));
        } catch(SocketException e) { e.printStackTrace(); }}@Override
    public void run(a) {
        while (true) {
            try {
                String msg = br.readLine();
                byte[] bytes = msg.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(this.toIp, this.toPort));
                // Send data
                socket.send(packet);
                if (msg.equals("bye")) {
                    break; }}catch(IOException e) { e.printStackTrace(); } } socket.close(); }}Copy the code
/ / the server
public class TalkReceive implements Runnable {

    DatagramSocket socket = null;

    private int port;

    private String msgForm;

    public TalkReceive(int port, String msgForm) {
        this.port = port;
        this.msgForm = msgForm;
        try {
            socket = new DatagramSocket(port);
        } catch(SocketException e) { e.printStackTrace(); }}@Override
    public void run(a) {
        while (true) {
            try {
                // Prepare to receive the package
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
                socket.receive(packet);
                // Disconnect the connection bye
                String msg = new String(packet.getData(), 0, packet.getLength());
                System.out.println(msgForm + ":" + msg);
                if ("bye".equals(msg)) {
                    break; }}catch(IOException e) { e.printStackTrace(); } } socket.close(); }}Copy the code
public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777."localhost".8888)).start();
        new Thread(new TalkReceive(9999."Teacher")).start(); }}Copy the code
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555."localhost".9999)).start();
        new Thread(new TalkReceive(8888."Students")).start(); }}Copy the code

Take a test and the results are as follows:

conclusion

  • UDP user datagram protocol is connectionless communication protocol. UDP data includes destination port number and source port number information. Because communication does not need to be connected, it can be broadcast.

  • UDP communication does not require the recipient’s confirmation. Therefore, UDP communication is unreliable and may cause packet loss. In practical applications, programmers are required to verify UDP communication.