贴代码是为了记忆。 //UdpSent.java import java.net.*; public class UdpSend { public static void main(String[] args) throws Exception { // TODO: Add your code here String str=/*"over";//*/"大家好,呵呵"; DatagramPacket dp=new DatagramPacket(str.getBytes(),str.getBytes().length,InetAddress.getByName("192.168.1.102"),3000); DatagramSocket ds=new DatagramSocket(); ds.send(dp); ds.close(); } } //UdpRecive.java import java.net.*; public class UdpRecive { public static void main(String[] args) throws Exception { // TODO: Add your code here DatagramSocket ds=new DatagramSocket(3000); byte [] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,1024); while(!(new String(dp.getData(),0,dp.getLength()).equals("over"))){ ds.receive(dp); String strReciev="The Message-->"+new String(dp.getData(),0,dp.getLength())+" from "+dp.getAddress().getHostAddress()+" 对方端口 "+dp.getPort(); System.out.println(strReciev); } } }