Communication program based on UDP protocol

Keywords: Java udp

1, What is UDP and what are its disadvantages?

UDP: user datagram protocol [connectionless protocol]
Disadvantages: the safety and reliability of data cannot be guaranteed.
Advantages: low consumption and high efficiency

  2, Classes and common methods needed to establish network communication program based on UDP

UDP based network communication program does not distinguish between client and server.
Java. Net. Datagram packet --- this class represents datagram packet. [package sent data / receive sent data]
Construction method:
    DatagramPacket(byte[] buf, int length) 
    Construct a datagram packet to receive the packet length of the length. [data packet receiving incoming data]
    DatagramPacket(byte[] buf, int length, InetAddress address, int port) 
    Constructs a datagram for sending packets of length. Packet length specifies the port number on the specified host.
Instance method:
     byte[]      getData() returns the data buffer.  
     int      getLength() returns the length of the data to be sent or received.  
     InetAddress      getAddress() returns the IP address of the computer that sent or received the datagram.
     int      getPort() returns the port number on the remote host from which the datagram was sent or received.  
Steps to create a UDP protocol communicator:
     Sender steps:
     1. Send the data to be sent through
       DatagramPacket(byte[]   buf, int   length, InetAddress   address, int   (2) the construction method shall be packaged
     2. Create DatagramSocket object through the construction method of DatagramSocket().
     3. The send method of datagramsocket object sends the packed datagram packet.
     4. Close datagram socket.
     Receiver steps
     1. Through datagram socket (int)   port) create a DatagramSocket object to receive data.
     2. Through datagram packet (byte []   buf, int   length) creates an empty datagram packet.
     3. Receive datagram packets into empty datagram packets by calling the receive method of the datagram socket object receiving data.
     4. Parse datagram packet
     5. Close datagram socket
Example 1: the client sends data to the server, and the server receives the data sent by the client
Sender

package com.wangxing.test1;

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

public class UDPsend {
	public static void main(String[] args) throws Exception{
		BufferedReader bufferedReader=null;
		int serverPort=3000;
		InetAddress address=null;
		byte data[]=null;
		//Pass the data to be sent through the construction method datagram packet (byte [] of datagram packet object   buf, int   length, InetAddress   address, int   port)
		DatagramPacket sendPackset=null;
		//The datagram packet object is obtained through the construction method of datagram socket()
		DatagramSocket sendSocket=null;
		//Get the transmitted data from the keyboard
		bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Please enter the content to send:");
		data=bufferedReader.readLine().getBytes();
		address=address.getLocalHost();
		sendPackset=new DatagramPacket(data,data.length,address,serverPort);
		sendSocket=new DatagramSocket();
		//3. The send method of datagramsocket object sends the packed datagram packet.
		sendSocket.send(sendPackset);
		//4. Close datagram socket.
		sendSocket.close();
	}
}

Receiving end:

package com.wangxing.test1;

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

public class UDPreceive {
	public static void main(String[] args) throws Exception{
		DatagramSocket receiveScoket=null;
		DatagramPacket receivepacket=null;
		int receivePort=3000;
		int len=0;
		byte data[]=new byte[1024];
		InetAddress localHost=null;
		int port;
		String info=null;
		//1. Through datagram socket (int)   port) create a DatagramSocket object to receive data.
		receiveScoket=new DatagramSocket(receivePort);
		System.out.println("The receiving end has been opened-------------------");
		//2. Through datagram packet (byte []   buf, int   length) creates an empty datagram packet.
		receivepacket=new DatagramPacket(data,data.length);
		//3. Receive datagram packets into empty datagram packets by calling the receive method of the datagram socket object receiving data.
		receiveScoket.receive(receivepacket);
		//4. Parse datagram packet
		//Get the parsed data in the datagram
		info=new String(receivepacket.getData());
		//Get the host IP of the data sender parsed in the datagram
		localHost=receivepacket.getAddress();
		//Get the port of the sending data program of the data sender parsed in the datagram
		port=receivepacket.getPort();
		System.out.println("from"+localHost+":"+port+"Data received on:"+info);
		//5. Close datagram socket
		receiveScoket.close();
	}
}

 

Example 2: the client continuously sends data to the server, and the server continuously receives the data sent by the client
Sender
package com.wangxing.test2;

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

public class UDPsend {
	public static void main(String[] args) throws Exception{
		BufferedReader bufferedReader=null;
		int serverPort=3000;
		InetAddress address=null;
		//Get data character
		String datastr=null;
		byte data[]=null;
		//Pass the data to be sent through the construction method datagram packet (byte [] of datagram packet object   buf, int   length, InetAddress   address, int   port)
		DatagramPacket sendPackset=null;
		//The datagram packet object is obtained through the construction method of datagram socket()
		DatagramSocket sendSocket=null;
		//Get the transmitted data from the keyboard
		bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		address=address.getLocalHost();
		sendSocket=new DatagramSocket();
		//Determine the variables that continue to execute
		boolean flag=true;
		while(flag){
			System.out.print("Please enter the content to send:");
			datastr=bufferedReader.readLine();
			data=datastr.getBytes();
			sendPackset=new DatagramPacket(data,data.length,address,serverPort);
			//3. The send method of datagramsocket object sends the packed datagram packet.
			sendSocket.send(sendPackset);
			if(datastr.equals("exit")){
				flag=false;
			}
		}
		//4. Close datagram socket.
		sendSocket.close();
	}
}
receiving end
 
package com.wangxing.test2;

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

public class UDPreceive {
	public static void main(String[] args) throws Exception{
		DatagramSocket receiveScoket=null;
		DatagramPacket receivepacket=null;
		int receivePort=3000;
		int len=0;
		byte data[]=new byte[1024];
		InetAddress localHost=null;
		int port;
		String info=null;
		//Determine the variables that continue to execute
		boolean flag=true;
		//1. Through datagram socket (int)   port) create a DatagramSocket object to receive data.
		receiveScoket=new DatagramSocket(receivePort);
		System.out.println("The receiving end has been turned on-------------------");
		//2. Through datagram packet (byte []   buf, int   length) creates an empty datagram packet.
		receivepacket=new DatagramPacket(data,data.length);
		while(flag){
			//3. Receive datagram packets into empty datagram packets by calling the receive method of the datagram socket object receiving data.
			receiveScoket.receive(receivepacket);
			//4. Parse datagram packet
			//Get the parsed data in the datagram
			info=new String(receivepacket.getData(),0,receivepacket.getLength());
			//Get the host IP of the data sender parsed in the datagram
			localHost=receivepacket.getAddress();
			//Get the port of the sending data program of the data sender parsed in the datagram
			port=receivepacket.getPort();
			System.out.println("from"+localHost+":"+port+"Data received on:"+info);
			if(info.equals("exit")){
				flag=false;
			}
		}
		
		//5. Close datagram socket
		receiveScoket.close();
	}
}

 

Example 3: create two-way data transmission between sender and client
 
package com.wangxing.test3;

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

public class UDPsend {
	public static void main(String[] args) throws Exception{
		BufferedReader bufferedReader=null;
		int serverPort=3000;
		InetAddress address=null;
		//Get data character
		String datastr=null;
		byte data[]=null;
		//Pass the data to be sent through the construction method datagram packet (byte [] of datagram packet object   buf, int   length, InetAddress   address, int   port)
		DatagramPacket sendPackset=null;
		DatagramPacket sendPackset2=null;
		//The datagram packet object is obtained through the construction method of datagram socket()
		DatagramSocket sendSocket=null;
		//Through DatagramSocket(int)   port) create a DatagramSocket object to receive data.
		DatagramSocket sendSocket2=null;
		//Create the port number returned by the receiving sender
		int receiveport=3001;
		//Through datagram packet (byte [])   buf, int   length) creates an empty datagram packet.
		DatagramPacket senPack=null;
		//Create an array that will save the sent and returned data
		byte receiveData[]=new byte[1024];
		//Create an array of returned data bytes
		byte reData[]=new byte[1024];
		//Creates a string that holds the returned byte array data
		String receiveInfo=null;
		//Get the transmitted data from the keyboard
		bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		address=InetAddress.getLocalHost();
		sendSocket=new DatagramSocket();
		//Receive returned data
		sendSocket2=new DatagramSocket(receiveport);
		//Create a heart datagram packet that receives the returned data
		sendPackset2=new DatagramPacket(receiveData,receiveData.length);
		//Determine the variables that continue to execute
		boolean flag=true;
		while(flag){
			System.out.print("Please enter the content to send:");
			datastr=bufferedReader.readLine();
			data=datastr.getBytes();
			sendPackset=new DatagramPacket(data,data.length,address,serverPort);
			//3. The send method of datagramsocket object sends the packed datagram packet.
			sendSocket.send(sendPackset);
			//Use the instance method receive() of datagram socket object to receive datagram packets
			sendSocket2.receive(sendPackset2);
			receiveData=sendPackset2.getData();
			receiveInfo=new String(receiveData,0,sendPackset2.getLength());
			System.out.println(receiveInfo);
			if(datastr.equals("exit")){
				flag=false;
			}
		}
		//4. Close datagram socket.
		sendSocket.close();
        sendSocket2.close();
	}
}
package com.wangxing.test3;

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

public class UDPreceive {
	public static void main(String[] args) throws Exception{
		DatagramSocket receiveScoket=null;
		DatagramSocket receiveScoket2=null;
		DatagramPacket receivepacket2=null;
		DatagramPacket receivepacket=null;
		int receivePort=3000;
		int len=0;
		byte arr[]=new byte[1024];
		InetAddress localHost=null;
		//Defines the port to send the segment program
		int port;
		//Save the port returned to the sender
		int sendPort=3001;
		//Create a byte array to get the data
		byte data[]=null;
		//Data string created
		String info=null;
		//Get the IP of the returned array
		InetAddress receiveAddress=InetAddress.getLocalHost();
		//Determine the variables that continue to execute
		boolean flag=true;
		//1. Through datagram socket (int)   port) create a DatagramSocket object to receive data.
		receiveScoket=new DatagramSocket(receivePort);
		//Through datagram packet (byte [])   buf, int   length)
		System.out.println("The receiving end has been turned on-------------------");
		//2. Through datagram packet (byte []   buf, int   length, InetAddress   address, int   port)
		receivepacket=new DatagramPacket(arr,arr.length);
		while(flag){
			//3. Receive datagram packets into empty datagram packets by calling the receive method of the datagram socket object receiving data.
			receiveScoket.receive(receivepacket);
			//4. Parse datagram packet
			//Get the parsed data in the datagram
			info=new String(receivepacket.getData(),0,receivepacket.getLength());
			//Get the host IP of the data sender parsed in the datagram
			localHost=receivepacket.getAddress();
			//Get the port of the sending data program of the data sender parsed in the datagram
			port=receivepacket.getPort();
			System.out.println("from"+localHost+":"+port+"Data received on:"+info);
			//Get the data and return it to the sender
			String xinxi="Receiver return---";
			data=(xinxi+info).getBytes();
			receivepacket2=new DatagramPacket(data,data.length,receiveAddress,sendPort);
			receiveScoket2=new DatagramSocket();
			receiveScoket2.send(receivepacket2);
			if(info.equals("exit")){
				flag=false;
			}
		}
		
		//5. Close datagram socket
		receiveScoket.close();
		receiveScoket2.close();
	}
}

 

Example 4: multiple senders to one receiver
 

Posted by santrowithu on Fri, 03 Dec 2021 04:32:14 -0800