import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //接收方 public class UDPChatUser_1 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int port = 10000; DatagramSocket Clintds = new DatagramSocket(port); byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length);
//接收方和发送方执行完之后,接收方一直处于阻塞状态 Clintds.receive(dp); byte[] bufByte = dp.getData(); System.out.println(new String(bufByte, 0, bufByte.length)); Clintds.close(); } } //-------------------------------------------------------------- import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //发送方 public class UDPCharUser_2 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub String str = "你好,UDP!"; DatagramSocket ds = new DatagramSocket(12306); byte[] strByte = str.getBytes(); //InetAddress ip = InetAddress.getLocalHost(); InetAddress ip = InetAddress.getByName("183.158.260.262"); int port = 10000; DatagramPacket dp = new DatagramPacket(strByte, strByte.length, ip , port); ds.send(dp); //System.out.println(new String(dp.getData(), 0, dp.getLength())); ds.close(); } }