UDP for network programming

8, UDP

1. Manipulate UDP in Java, and use Java. UDP in JDK Net package can easily control user data packets.

2.DatagramSocket class: create Socket instances that receive and send UDP
Datagram socket(): create an instance. It is usually used for client programming. It has no specific listening port and only uses a temporary port.
Datagram socket (int Port): create an instance and listen to the messages of Port port.
Datagram socket (int port, InetAddress, LocalAddr): This is a very useful builder. When a machine has more than one IP address, the instance created by it only receives messages from LocalAddr

Receive (datagram packet d): receive data packets into D. The receive method generates a "block".
Send (datagram packet d): send the message d to the destination.
setSoTimeout(int timeout): sets the timeout, in milliseconds.
close(): close datagram Socket. When an application exits, it usually takes the initiative to release resources and close the Socket. However, due to abnormal exit, resources may not be recycled. Therefore, you should actively use this method to close the Socket when the program is completed, or close the Socket after an exception is caught and thrown
Note: 1 When creating a DatagramSocket class instance, if the port has been used, an exception of SocketException will be thrown and the program will terminate illegally. This exception should be caught carefully.

3. "Blocking" is a professional term. It will generate an internal loop that causes the program to pause at this place until a condition is triggered.

4. Datagram packet: used to process messages, package byte array, target address, target port and other data into messages, or disassemble messages into byte array.
Datagram packet (byte [] buf, int length, InetAddress, addr, int port): take the data with length from buf array to create a data packet object. The target is addr address and port.
Datagram packet (byte [] buf, int offset, int length, InetAddress, address, int port): from the buf array, take out the data with a length of offset and create a packet object. The target is addr address and port.
Datagram packet (byte [] buf, int offset, int length): load the data in the data packet starting from offset and length into the buf array.
Datagram packet (byte [] buf, int length): load the length data in the data packet into the buf array.
getData(): it obtains the byte array code of the message from the instance.

(1) . send message

send message. You don't need to connect, but you need the other party's address

Sender

package com.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//No connection to the server is required
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1. Create a socket
        DatagramSocket socket = new DatagramSocket();
        //2. Build a package
        String msg = "Helloļ¼ŒThe server!";
        //3. To whom
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //Data, starting from the length of the data, to whom
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length,localhost,port);
        //3. Send packet
        socket.send(packet);
        //4. Close the flow
        socket.close();
    }
}

receiving end

package com.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//Need to wait for client connection!!!
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //Open port
        DatagramSocket socket = new DatagramSocket(9090);
        //Accept packet
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);//Blocking acceptance
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));


        //Close connection
        socket.close();
    }
}

(2) . send message circularly

Receiver

package com.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while(true){
            //Ready to accept the package
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            //Receive package when blocked
            socket.receive(packet);
            //Disconnect bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);
            System.out.println(receiveData);
            if(receiveData.equals("bye")){
                break;
            }
        }
        socket.close();

    }
}

Sender

package com.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        //Prepare data: the console reads system in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length, new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if(data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

Start sequence: receive first and then send. Check success: enter a string at the sender and view the message of the receiver

(3) Mutual consultation

Combined with multithreading

Conversation sender

package com.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromIP, String toIP, int toPort) {
        this.fromPort = fromIP;
        this.toIP = toIP;
        this.toPort = toPort;
        try{
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try{
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length, new InetSocketAddress(this.toIP,this.toPort));
                socket.send(packet);
                if(data.equals("bye")){
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

Conversation receiver

package com.chat;

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

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;

    private int port;//Port number
    private String msfFrom;

    public TalkReceive(int port, String msfFrom) {
        this.port = port;
        this.msfFrom = msfFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){

            try {
                //Ready to accept the package
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                //Receive package when blocked
                socket.receive(packet);
                //Disconnect bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msfFrom+": "+receiveData);
                if(receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

Student side

package com.chat;

public class TalkSudent {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"teacher")).start();

    }
}

Teacher end

package com.chat;

public class TalkTeaaher {
    public static void main(String[] args) {
        //Two processes, sending port and arriving port
        //The port at the time of receiving. Where does it come from
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"student")).start();
    }
}

Result run chart

Added by boogybren on Fri, 24 Dec 2021 21:38:52 +0200