JAVA------UDP send data and receive data

UDP receives data and sends data

Steps to send data through UDP:

  1. Create the sender's Socket object (DatagramSocket)
  2. Create data and package data
  3. Call the method of the DatagramSocket object to send data
  4. Close sender

Look at the code demo:

package UDP;

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

public class SendDemo {
    
    
	public static void main(String[] args) throws IOException{
    
    
		//创建发送端的Socket对象(DatagramSocket)
		DatagramSocket ds=new DatagramSocket();
		
		//创建数据,并将数据打包
		//DatagramPacket(byte[] buf,int length,InetAddress address,int port)
		//构造一个数据包,发送长度为length的数据包到指定主机上的指定端口号
		byte[] bys="hello,udp".getBytes();
		int len=bys.length;
		InetAddress address=InetAddress.getByName("192.168.223.1");
		int port=10086;//端口号
		DatagramPacket dp=new DatagramPacket(bys,len,address,port);
		 
		
		//调用DatagramSocket对象的方法发送数据
		//void send(DatagramSocket p) 从此套接字发送数据包
		ds.send(dp);
		
		//关闭发送端
		ds.close();
	}
}

Steps for UDP to receive data:

  1. Create the receiving end of the Socket object (DatagramSocket)
  2. Create a data package to receive data
  3. Call the method of the DatagramSocket object to receive data
  4. Close sender

Look at the code directly:

package UDP;

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

public class RecriveDemo {
    
    
	public static void main(String[] args) throws IOException{
    
    
		//创建接受端的Socket对象(DatagramSocket)
		//DatagramSocket(int port)构造数据报套接字并将其绑定到本地主机的指定端口
		DatagramSocket ds=new DatagramSocket(10086);
		
		//创建数据包,用于接受数据
		//DatagramPacket(byte[] buf,int length)构造一个DatagramPacket用于接受长度为lenth数据包
		byte[] bys=new byte[1024];
		DatagramPacket dp=new DatagramPacket(bys, bys.length);
		
		//调用DatagramSocket对象的方法接收数据
		ds.receive(dp);
		 
		//解析数据包,并把数据在控制台显示
		//byte[] getData()返回数据缓冲区
		byte datas[]=dp.getData();
		//int getlength()返回要发送的数据的长度或接收到的数据长度
		int len=dp.getLength();
		String dataString=new String(datas,0,len);
		System.out.println("数据是:"+dataString);
		
		//关闭发送端
		ds.close();
	}

}

Here the IP address is my local IP, which is to send data to myself, and then the receiving end accepts it, and then the sent data "hello, udp" can be received

Guess you like

Origin blog.csdn.net/weixin_45102820/article/details/113781049