UDP_Socket
- 单向传输数据
/*Server.java*/ import java.net.*; public class Server { public static void main(String[] args) throws Exception { byte buf[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); DatagramSocket ds = new DatagramSocket(8888); while(true) { ds.receive(dp); System.out.println(new String(buf, 0, dp.getLength())); } } }
/*Client.java*/ import java.net.*; public class Client { public static void main(String[] args) throws Exception { byte[] buf = (new String("Hello")).getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 2333)); DatagramSocket ds = new DatagramSocket(8888); ds.send(dp); ds.close(); } }