Java Network Programming -- UDP

Posted by kwstephenchan on Wed, 09 Feb 2022 19:24:03 +0100

UDP

UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but these two sockets are only the objects to send and receive data. Therefore, for both sides of communication based on UDP protocol, there is no so-called concept of client and server

Java provides DatagramSocket class as a Socket based on UDP protocol

UDP send data

Construction method

Method nameexplain
DatagramSocket()Create a datagram socket and bind it to any available port on the native address
DatagramPacket(byte[] buf,int len,InetAddress add,int port)Create a packet and send a packet with a length of len to the specified port of the specified host

correlation method

Method nameexplain
void send(DatagramPacket p)Send datagram packet
void close()Close datagram socket
void receive(DatagramPacket p)Accept datagram packets from this socket

To send data

UDP receive data

Construction method

Method nameexplain
DatagramPacket(byte[] buf, int len)Create a datagram packet to receive packets with length len

correlation method

Method nameexplain
byte[] getData()Return data buffer
int getLength()Returns the length of data to be sent or received

Steps to receive data

  • Create a Socket object (datagram Socket) at the receiving end

  • Create a packet to receive data

  • Call the method of DatagramSocket object to receive data

  • Analyze the data package and display the data on the console

  • Close the receiver

code implementation

Receiver ServerDemo01

public class ServerDemo01 {
    public static void main(String[] args) throws IOException {
        //1. Create the Socket object (DatagramSocket) of the receiving end
        DatagramSocket ds = new DatagramSocket(10000);

        //2. Create a packet for receiving data
        byte[] bytes = new byte[1024];

        //3. Call the method of DatagramSocket object to receive data
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);

        //4. Analyze the data package and display the data on the console
        ds.receive(dp);
        byte[] data = dp.getData();
        System.out.println(new String(data));

        //5. Close the receiver
        ds.close();
    }
}

Sender ClientDemo01

public class ClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1. Create the Socket object (DatagramSocket) of the sender
        //Use null parameter - indicates that a random parameter is used
        DatagramSocket ds = new DatagramSocket();

        //2. Create data and package it
        //DatagramPacket(byte[] buf,int len,InetAddress add,int port)
        String s = "Send: my first network program";
        byte[] bytes = s.getBytes();
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int port = 10000;
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);

        //3. Call the method of DatagramSocket object to send data
        ds.send(dp);

        //4. Close the sender
        ds.close();
    }
}

Note: be sure to run ServerDemo01 first, then ClientDemo01, and print the data transmitted by UDP on the console of ServerDemo01.  

UDP communication program exercise

Case requirements

UDP sending data: the data comes from the keyboard input until the input data is 886, and the sending data ends

UDP receiving data: because the receiving end does not know when the sending end will stop sending, it adopts dead loop receiving

code implementation

Receiver ServerDemo02

//Receiving end
public class ServerDemo02 {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10000);

        while(true) {
            byte[] bytes = new byte[1024];

            DatagramPacket dp = new DatagramPacket(bytes,bytes.length);

            ds.receive(dp);

            byte[] data = dp.getData();
            int length = dp.getLength();
            System.out.println("The received content is:");
            System.out.println(new String(data,0,length));
        }
        //ds.close();
    }
}

Sender ClientDemo02

//Sender
public class ClientDemo02 {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        DatagramSocket ds = new DatagramSocket();

        while(true) {
            System.out.println("Please enter what you will send:");
            String s = sc.nextLine();
            if("886".equals(s)){
                break;
            }
            byte[] bytes = s.getBytes();
            InetAddress address = InetAddress.getByName("127.0.0.1");
            int port = 10000;
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);
            ds.send(dp);
        }
        ds.close();
    }
}

Three communication modes of UDP

  • unicast

    Unicast is used for end-to-end communication (point-to-point transmission) between two hosts

  • Multicast

    Multicast is used to communicate with a specific group of hosts

  • radio broadcast

    Broadcast is used for data communication between one host and all hosts on the whole LAN

UDP multicast implementation

The sending end of multicast is similar to unicast, but the difference lies in the receiving end!

Implementation steps

  • Sender

  1. Create a Socket object (datagram Socket) at the sending end
  2. Create data and package the data (datagram packet)
  3. Call the method of DatagramSocket object to send data (in unicast, it is sent to the computer with the specified IP, but in multicast, it is sent to the multicast address)
  4. Release resources
  • receiving end

  1. Create receiver Socket object (MulticastSocket)
  2. Create a box to receive data
  3. Bind the current computer to a multicast address
  4. Receive data into the box
  5. Parse the packet and print the data
  6. Release resources

code implementation

 

 

Topics: Java network udp