This is the seventh day of my participation in the More text Challenge. For details, see more text Challenge

This article is participating in the “Java Theme Month – Java Development in action”. See the link to the event for more details


preface

In life, we often receive harassing phone calls and harassing text messages. Harassing phone calls can be abstractly understood as TCP, while harassing text messages can be abstractly understood as UDP. As long as I know your address, I can directly send it whether you are willing to receive it or not and whether it is successful or not

What is a UDP?

  • User Datagram Protocol (UDP) is a connectionless protocol used to process data packets on the network, just like TCP. In the OSI model, the fourth layer, the transport layer, is one layer above the IP protocol. UDP has the disadvantage of not providing packet grouping, assembly, and sorting, which means that once a packet is sent, it is impossible to know whether it arrived safely and intact.

  • It has the following characteristics:

      1. Connectionless oriented
    • First of all, UDP does not require a three-way handshake to establish a connection as TCP does. You can send data when you want. In addition, it is only a carrier of data packets and does not split or splice data packets.

    • Specifically:

    • At the sending end, the application layer passes the data to the UDP protocol at the transport layer, which only adds a UDP header to the data and then passes it to the network layer

At the receiving end, the network layer passes the data to the transport layer. UDP only removes the IP packet header and passes the data to the application layer without any splicing operation

  • There are unicast, multicast, broadcast functions

    • UDP not only supports one-to-one transmission mode, but also supports one-to-many, many-to-many, and many-to-one modes. In other words, UDP provides unicast, multicast, and broadcast functions.
  • UDP is packet oriented

    • The UDP packet sent by the sender to the application program adds the header and delivers the packet to the IP layer. UDP does not merge or split the packets sent by the application layer, but retains the packet boundaries. Therefore, the application must select the appropriate size of the packet
  • Unreliability.

    • First of all, unreliability is reflected in no connection, communication does not need to establish a connection, want to send, such a situation is certainly not reliable.

    • The data is passed as it is received, without backing up the data, and without caring whether the data has been received correctly.

    • Again, the network environment is up and down, but UDP, because there is no congestion control, will always send data at a constant speed. Even if the network is not good, the transmission rate will not be adjusted. The disadvantage of this implementation is that it may cause packet loss in the case of poor network conditions, but the advantage is also obvious. In some real-time scenarios (such as teleconference), it is necessary to use UDP instead of TCP.

First, UDP to achieve sending messages

Client-side code simulation:

/** * Client */
public class UdpClient {
    public static void main(String[] args) throws Exception{
        // Bind the socket to port 8888 at the same time
        DatagramSocket socket = new DatagramSocket(8888);

        // The data packet is available from the console
        //String MSG = "Hello, Sir, would you like to have a down payment of 88000 yuan?" ;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {// Get the console data and turn it into a byte array
            byte[] msg = bufferedReader.readLine().getBytes();
            // To whom?
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port = 7777;
            // The parameters are packet, start location, end location, IP, and port
            DatagramPacket packet = new DatagramPacket(msg,0,msg.length,ip,port);

            // Start sending
            socket.send(packet);
            // If the other party sends goodbye, we will disconnect
            if (bufferedReader.readLine().equals("Bye bye")) {break; }}// Close the connectionsocket.close(); }}Copy the code

Server code simulation:

/** * Server */
public class UdpServer {
    public static void main(String[] args) throws Exception{
        // Develop the port
        DatagramSocket socket = new DatagramSocket(7777);
        // Receive the packet
        byte[] buffer = new byte[1024];

        while (true){
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            socket.receive(packet); // Block receive


            byte[] bytes = packet.getData();
            String msg = new String(bytes,0,bytes.length);
            System.out.println(msg);

            // Disconnect
            if (msg.equals("Bye bye")) {break; }}// Close the connectionsocket.close(); }}Copy the code

Client execution result:Server execution result:

So far, the basic function of harassing SMS has been realized, actually can realize two-way chat. I will not expand it here


The road ahead will be long and long, but I will keep searching. If you think I blogger’s writing is good! Writing is not easy, please like, follow, comment to encourage the blogger ~hahah