目标效果:
注意在接收端打印数据
UDPSend.java(发送端):
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world”。
* @author Vivinia
*/
//发送端
public class UDPSend {
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket(3000); //创建一个DatagramSocket对象
String str="Hello, world"; //要发送的数据
DatagramPacket dp=new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),8001);//创建一个要发送的数据包,包括数据,长度,接收端的ip及端口号
System.out.println("发送消息");
ds.send(dp); //发送数据
ds.close(); //释放资源
}
}
UDPReceive.java(接收端):
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接收端
public class UDPReceive {
public static void main(String[] args) throws Exception{
byte[] buf=new byte[1024]; //创建一个1024的字节数组,用于接收数据
DatagramSocket ds=new DatagramSocket(8001); //定义一个DatagramSocket对象,监听的端口号为8954
DatagramPacket dp=new DatagramPacket(buf,1024); //定义一个DatagramPacket对象,用于接收数据
System.out.println("等待接收数据");
ds.receive(dp); //等待接收数据,没有则会阻塞
String str=new String(dp.getData()); //获取接收到的消息
System.out.println(str);
ds.close();
}
}