import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPsend { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub DatagramSocket ds=new DatagramSocket(); String string="hello world"; DatagramPacket dp=new DatagramPacket(string.getBytes(), string.length(),InetAddress.getByName("127.0.0.1"),4321); ds.send(dp); ds.close(); }}
import java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPrecv { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub DatagramSocket ds=new DatagramSocket(4321); byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf, 1024); ds.receive(dp); String strRecv=new String(dp.getData(),0,dp.getLength())+"from"+dp.getAddress().getHostAddress()+":"+dp.getPort(); System.out.println(strRecv); ds.close(); }}