UDP network programming of Socket socket one-way and two-way exception handling normal communication between two people based on UDP

Posted by peerData on Fri, 24 Dec 2021 14:31:49 +0100

UDP network programming one-way and two-way exception handling of Socket socket

Socket

  • It is used to describe the IP address and port. It is the handle of the communication chain. The application sends or responds to the network request through the Socket
  • It is the basic operation unit of network communication supporting TCP/IP protocol,
  • It is an abstraction of the endpoint for two-way communication between application processes on different hosts in the network. It contains five kinds of information: the protocol used for the connection, the local IP, that is, the process interface PORT, the remote host IP and the process interface PORT.
  • A socket is the end of process communication on the network, which provides a mechanism for application layer processes to exchange data using network protocol.
  • In terms of its position, the socket connects the application process and the network protocol stack. It is the interface for the application to communicate through the network protocol and the interface for the application to interact with the network protocol root.

UDP

UDP is a simple protocol based on IP, which is not reliable. There is no flow control, no response confirmation mechanism, and can not solve the problems of packet loss, retransmission and wrong sequence; But it is also more simple and lightweight. It does little special except the ability to send packets to applications and allow them to architecture their own protocols at the required level. The addresses of the sender and the receiver are equal.

Sender: datagram socket send: datagram packet
Receiver: datagram socket receiving: datagram packet

Datagram packet constructor and method:

constructor

  • DatagramPacket(byte[] buf, int length)

Construct datagram packets to receive packets with length

  • DatagramPacket(byte[] buf, int length, InetAddress address, int port)

Construct datagram packet, which is used to send the packet with length to the specified port number on the specified host

method

  • InetAddress getAddress()

    • Returns the IP address of a machine to which this datagram will be sent or received.
  • byte[] getData()

    • Returns the data buffer.
  • int getLength()

  • Returns the length of data to be sent or received.

  • int getPort()

    • Returns the port number of a remote host to which this datagram will be sent or received.

Next is the UDP communication instance. The exception will not be handled for the time being, and the throwing pot will be thrown directly. During operation, start the receiver first and then the sender, otherwise packet loss will occur

Unidirectional communication

Receiver

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receive {
    public static void main(String[] args) throws IOException {
        System.out.println("Teacher online");
        //1. Create socket: specify the port of the receiver
        DatagramSocket ds = new DatagramSocket(8888);

        //2. There is an empty packet intended to receive packets from the other party:
        byte[] b = new byte[1024];
        DatagramPacket dp = new DatagramPacket(b,b.length);

        //3. Receive the other party's data packet and fill it in our dp data packet
        ds.receive(dp);//After receiving, there will be filled content in dp

        //4. Take out data:
        byte[] data = dp.getData();
        String s = new String(data,0,dp.getLength());//dp.getLength() array is the valid length in the package
        System.out.println("The student said to me:"+s);

        //5. Close resources:
        ds.close();
    }
}

Sender

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Send {
    public static void main(String[] args) throws IOException {
        System.out.println("Student Online");
        //1. Prepare socket: specify the port number of the sender
        DatagramSocket ds = new DatagramSocket(8889);

        //2. Prepare data package
        String str = "Hello";
        byte[] bytes = str.getBytes();
        // Datagram packet (byte [] packet data. int packet length. InetAddress destination address. int destination port number)
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);

        //send out:
        ds.send(dp);
        System.out.println("has been sent");
        //close resource
        ds.close();
    }
}
Communication process
Send:
Student Online
 has been sent

Receive:
Teacher online
 The student said to me: Hello

Two way communication

Receiver

public class Receive {
    public static void main(String[] args) throws IOException {
        System.out.println("Teacher online");
        //1. Create socket: specify the port of the receiver
        DatagramSocket ds = new DatagramSocket(9999);

        //2. There is an empty packet intended to receive packets from the other party:
        byte[] b = new byte[1024];
        DatagramPacket dp = new DatagramPacket(b,b.length);

        //3. Receive the other party's data packet and fill it in our dp data packet
        ds.receive(dp);//After receiving, the dp will be filled with content

        //4. Take out data:
        byte[] data = dp.getData();
        String s = new String(data,0,dp.getLength());
        System.out.println("The student said:"+s);
        //The teacher replied:
        Scanner sc = new Scanner(System.in);
        System.out.print("I:");
        String str = sc.next();
        byte[] bytes = str.getBytes();
        //Encapsulate the data and specify the student's IP and port number
        DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
        //send out:
        ds.send(dp2);

        //5. Close resources:
        ds.close();
    }
}

Sender

public class Send {
    public static void main(String[] args) throws IOException {
        System.out.println("Student Online");
        //1. Prepare socket: specify the port number of the sender
        DatagramSocket ds = new DatagramSocket(8888);
        //2. Prepare data package
        Scanner sc = new Scanner(System.in);
        System.out.print("I:");
        String str = sc.next();
        byte[] bytes = str.getBytes();

        // Datagram packet (byte [] packet data. int packet length. InetAddress destination address. int destination port number)
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
        //send out:
        ds.send(dp);
        //Receive the information sent back by the teacher:
        byte[] b = new byte[1024];
        DatagramPacket dp2 = new DatagramPacket(b,b.length);
        ds.receive(dp2);//After receiving, dp2 will be filled with content
        //Fetch data:
        byte[] data = dp2.getData();
        String s = new String(data,0,dp2.getLength());//dp.getLength() is the valid length in the array package
        System.out.println("The teacher said:"+s);
        //close resource
        ds.close();
    }
}
Communication process
Student Online
 Me: I am Fyz
 The teacher said: I am Teacher

Teacher online
 The student said: I am Fyz
 Me: I am Teacher Wang

exception handling

Take two-way communication as an example

try-catch-fianlly

Receiver

public class Receive {
    public static void main(String[] args){
        System.out.println("Teacher online");
        //1. Create socket: specify the port of the receiver
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9999);
            //2. There is an empty packet intended to receive packets from the other party:
            byte[] b = new byte[1024];
            DatagramPacket dp = new DatagramPacket(b,b.length);
            //3. Receive the other party's data packet and fill it in our dp data packet
            ds.receive(dp);//After receiving, the dp will be filled with content
            //4. Take out data:
            byte[] data = dp.getData();
            String s = new String(data,0,dp.getLength());
            System.out.println("The student said:"+s);
            //The teacher replied:
            Scanner sc = new Scanner(System.in);
            System.out.print("I:");
            String str = sc.next();
            byte[] bytes = str.getBytes();
            //Encapsulate the data and specify the student's IP and port number
            DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
            //send out:
            ds.send(dp2);
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{//5. Close resources:
            assert ds != null;
            ds.close();
        }
    }
}

Sender

public class Send {
    public static void main(String[] args){
        System.out.println("Student Online");
        //1. Prepare socket: specify the port number of the sender
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(8888);
            //2. Prepare data package
            Scanner sc = new Scanner(System.in);
            System.out.print("I:");
            String str = sc.next();
            byte[] bytes = str.getBytes();

// Datagram packet (byte [] packet data. int packet length. InetAddress destination address. int destination port number)
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
            //send out:
            ds.send(dp);
            //Receive the information sent back by the teacher:
            byte[] b = new byte[1024];
            DatagramPacket dp2 = new DatagramPacket(b,b.length);
            ds.receive(dp2);//After receiving, dp2 will be filled with content
            //Fetch data:
            byte[] data = dp2.getData();
            String s = new String(data,0,dp2.getLength());//dp.getLength() array is the valid length in the package
            System.out.println("The teacher said:"+s);
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{ //close resource
            assert ds != null;
            ds.close();
        }
    }
}

try-with-resource

Receiver

public class Receive {
    public static void main(String[] args){
        System.out.println("Teacher online");
        //1. Create socket: specify the port of the receiver
        try (DatagramSocket ds = new DatagramSocket(9999);){
            //2. There is an empty packet intended to receive packets from the other party:
            byte[] b = new byte[1024];
            DatagramPacket dp = new DatagramPacket(b,b.length);
            //3. Receive the other party's data packet and fill it in our dp data packet
            ds.receive(dp);//After receiving, the dp will be filled with content
            //4. Take out data:
            byte[] data = dp.getData();
            String s = new String(data,0,dp.getLength());
            System.out.println("The student said:"+s);
            //The teacher replied:
            Scanner sc = new Scanner(System.in);
            System.out.print("I:");
            String str = sc.next();
            byte[] bytes = str.getBytes();
            //Encapsulate the data and specify the student's IP and port number
            DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
            //send out:
            ds.send(dp2);
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Sender

public class Send {
    public static void main(String[] args){
        System.out.println("Student Online");
        //1. Prepare socket: specify the port number of the sender
        try (DatagramSocket ds = new DatagramSocket(8888);){
            //2. Prepare data package
            Scanner sc = new Scanner(System.in);
            System.out.print("I:");
            String str = sc.next();
            byte[] bytes = str.getBytes();

            // Datagram packet (byte [] packet data. int packet length. InetAddress destination address. int destination port number)
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
            //send out:
            ds.send(dp);
            //Receive the information sent back by the teacher:
            byte[] b = new byte[1024];
            DatagramPacket dp2 = new DatagramPacket(b,b.length);
            ds.receive(dp2);//After receiving, dp2 will be filled with content
            //Fetch data:
            byte[] data = dp2.getData();
            String s = new String(data,0,dp2.getLength());//dp.getLength() array is the valid length in the package
            System.out.println("The teacher said:"+s);
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Normal communication (always connected)

Receiver

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Receive {
    public static void main(String[] args){
        System.out.println("Teacher online");
        //1. Create socket: specify the port of the receiver
        try (DatagramSocket ds = new DatagramSocket(9999);){
           while(true){
               //2. There is an empty packet intended to receive packets from the other party:
               byte[] b = new byte[1024];
               DatagramPacket dp = new DatagramPacket(b,b.length);
               //3. Receive the other party's data packet and fill it in our dp data packet
               ds.receive(dp);//After receiving, the dp will be filled with content
               //4. Take out data:
               byte[] data = dp.getData();
               String s = new String(data,0,dp.getLength());
               System.out.println("The student said:"+s);
               if (s.equals("bye")){
                   System.out.println("Students have been offline, chat terminated");
                   break;
               }
               //The teacher replied:
               Scanner sc = new Scanner(System.in);
               System.out.print("I:");
               String str = sc.nextLine();
               byte[] bytes = str.getBytes();
               //Encapsulate the data and specify the student's IP and port number
               DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
               //send out:
               ds.send(dp2);
           }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Sender

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Send {
    public static void main(String[] args){
        System.out.println("Student Online");
        //1. Prepare socket: specify the port number of the sender
        try (DatagramSocket ds = new DatagramSocket(8888);){
            while(true){
                //2. Prepare data package
                Scanner sc = new Scanner(System.in);
                System.out.print("I:");
                String str = sc.nextLine();
                byte[] bytes = str.getBytes();
                // Datagram packet (byte [] packet data. int packet length. InetAddress destination address. int destination port number)
                DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
                //send out:
                ds.send(dp);
                if (str.equals("bye")){
                    System.out.println("You're offline");
                    break;
                }
                //Receive the information sent back by the teacher:
                byte[] b = new byte[1024];
                DatagramPacket dp2 = new DatagramPacket(b,b.length);
                ds.receive(dp2);//After receiving, dp2 will be filled with content
                //Fetch data:
                byte[] data = dp2.getData();
                String s = new String(data,0,dp2.getLength());//dp.getLength() array is the valid length in the package
                System.out.println("The teacher said:"+s);
            }

        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Communication instance
Send PartyReceive party
go onlineStudent OnlineTeacher online
Hello, Teacher Wang
Hello, Fyz
I wonde what about the examination paper on C++
This got five more in the final exam papers
bye
OfflineYou're offlineStudents have been offline, chat terminated
    | Hello, Fyz                                  |

| | I wonde what about the examination paper on C++ | |
| | | This got five more in the final exam papers |
|| bye ||
|Offline | you have been offline | students have been offline, chat is terminated|

Topics: Java network socket udp