发送端
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 {
//创建发送端对象
DatagramSocket ds=new DatagramSocket();
//创建数据,并把数据打包
byte[] bys= "hello,world,java,我来了".getBytes();
DatagramPacket dp=new DatagramPacket(bys,bys.length,InetAddress.getByName("192.168.56.1"),10086);
//发送数据
ds.send(dp);
//关闭发送端
ds.close();
}
}
接收端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receive {
public static void main(String[] args) throws IOException {
//创建接受端
DatagramSocket ds = new DatagramSocket(10086);
//创建一个数据包,接收数据
byte[] bys=new byte[1024];
DatagramPacket dp = new DatagramPacket(bys,bys.length);
//调用方法接收数据
ds.receive(dp);
//解析数据包,并在控制台显示
byte[] datas=dp.getData();
System.out.println("数据是:"+new String(datas,0,dp.getLength()));
//关闭接收端
ds.close();
}
}