import java.net.*; class netDemo { public static void main(String[] args)throws Exception { System.out.println("发送数据。。。。。"); DatagramSocket ds=new DatagramSocket(); String str="哥来了"; byte[] buf=str.getBytes(); DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),1000); ds.send(dp); ds.close(); } }
import java.net.*; class netDemo { public static void main(String[] args)throws Exception { System.out.println("接收数据。。。。。"); DatagramSocket ds=new DatagramSocket(1000); byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,buf.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); int port=dp.getPort(); String text=new String(dp.getData(),0,dp.getLength()); ds.close(); System.out.println(ip+""+port+""+text); } public static void Method1() { } }