java学习笔记-网络编程
服务端
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 4 5 public class UDPrece { 6 7 /** 8 * @param args 9 * @throws Exception 10 */ 11 public static void main(String[] args) throws Exception { 12 13 14 //建立端点 指定端口 15 DatagramSocket ds =new DatagramSocket(9999); 16 17 while(true){ 18 byte[] buf=new byte[1024]; 19 20 //定义数据包 用于存储数据 21 DatagramPacket dp=new DatagramPacket(buf, buf.length); 22 23 24 25 //接收数据 存储到指定数据包中 26 ds.receive(dp); 27 28 29 //从数据包中提取 IP 端口 数据等信息 30 String ip=dp.getAddress().getHostAddress(); 31 int port=dp.getPort(); 32 String data=new String(dp.getData(),0,dp.getLength()); 33 34 35 System.out.println("IP: "+ip +" Port: "+port+" data: "+ data); 36 37 38 //关闭资源 39 40 } 41 // ds.close(); 42 43 44 45 46 } 47 48 }
客户端
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 import java.net.InetAddress; 4 5 6 public class UDPsend { 7 8 /** 9 * @param args 10 * @throws Exception 11 */ 12 public static void main(String[] args) throws Exception { 13 14 15 //建立端点 指定端口 16 DatagramSocket ds=new DatagramSocket(8888); 17 18 //将数据封装给数据包 19 byte[] buf=new byte[1024]; 20 buf="I'm a boy !".getBytes();/*localhost*/ 21 DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName("10.12.205.33"),9999); 22 23 24 // 发送数据包 25 ds.send(dp); 26 ds.close(); 27 28 } 29 30 }