1 /** 2 * 发送方 3 */ 4 public class DataGramSender { 5 6 public static void main(String[] args) { 7 try { 8 //9999向外发的端口号 9 DatagramSocket socket = new DatagramSocket(9999); 10 int i=1; 11 while(true){ 12 String content="Tom"+i; 13 byte[] buf=content.getBytes(); 14 //创建数据报表 15 DatagramPacket packet = new DatagramPacket(buf, buf.length); 16 //设置包要发送的地址和端口号 17 packet.setAddress(InetAddress.getByName("localhost")); 18 packet.setPort(8888); 19 socket.send(packet); 20 System.out.println("sent"+content); 21 Thread.sleep(1000); 22 i++; 23 } 24 } catch (Exception e) { 25 // TODO Auto-generated catch block 26 e.printStackTrace(); 27 } 28 } 29 } 30 31 32 /** 33 * 接收方 34 * 35 */ 36 public class DataGramRece { 37 public static void main(String[] args) { 38 try { 39 //创建数据报套接字 40 DatagramSocket socket = new DatagramSocket(8888); 41 byte[] buf=new byte[1024*64]; 42 DatagramPacket packet = new DatagramPacket(buf, buf.length); 43 while(true){ 44 socket.receive(packet); 45 //得到收到的数据长度 46 int len=packet.getLength(); 47 System.out.println(new String(buf,0,len)); 48 } 49 } catch (Exception e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 } 54 }