发送端: package demo_03_15; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import demo_03_14.inetAddress; public class UDPsend { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println("发送数据中…………"); //第一步:创建UDPSocket DatagramSocket ds = new DatagramSocket(); //第二步:创建InetAddress对象 InetAddress ip = InetAddress.getByName("localhost"); //第三步:创建UDP数据包 String data = "fuck you java , php , python"; byte[] buf = data.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, ip, 9000); //第四步:发送UDP数据包 ds.send(dp); //第五步:关闭资源 ds.close(); } } 接收端: package demo_03_15; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPreceive { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println("接收数据中…………"); //第一步:创建接收udpsocket DatagramSocket ds = new DatagramSocket(10000); //第二步:创建存储包的udppacket byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); ds.receive(dp); //阻塞式 //第三步:解析接收到的udp包 String host = dp.getAddress().getHostName(); int port = dp.getPort(); String data = new String(dp.getData(),0,dp.getLength()); //第四步:关闭资源 ds.close(); System.out.println(host+" "+port+" "+data); } }