1 import java.net.*; 2 import java.io.*; 3 class UDPSDemo 4 { 5 public static void main(String[]args) throws Exception 6 { 7 //创建发送端socket服务 8 DatagramSocket ds=new DatagramSocket(); 9 //准备发送的数据包 10 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 11 String line; 12 while((line=br.readLine())!=null) 13 { 14 if("886".equals(line)) 15 break; 16 byte[] buf=line.getBytes(); 17 //数据包 18 DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("localhost"),10000); 19 //发送 20 ds.send(dp); 21 } 22 ds.close(); 23 } 24 } 25 26 class UDPRDemo 27 { 28 public static void main(String[]args) throws Exception 29 { 30 //创建接收端socket服务,明确监听端口号 31 DatagramSocket ds=new DatagramSocket(10000); 32 while(true) 33 { 34 //准备接收数据的数据包 35 byte[] buf=new byte[1024]; 36 DatagramPacket dp=new DatagramPacket(buf,buf.length); 37 //接收 38 ds.receive(dp); 39 String address=dp.getAddress().getHostAddress(); 40 String data=new String(dp.getData(),0,dp.getLength()); 41 System.out.println("IP:"+address); 42 System.out.println("Data:"+data); 43 } 44 } 45 }
时间: 2024-11-10 20:06:17