创建UDP客户端和服务器
import java.net.*; /* *来 自 n o w j a v a . c o m */ class WriteServer { public static int serverPort = 1234; public static int clientPort = 1235; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[] = new byte[buffer_size]; // UDP Server Method public static void TheServer() throws Exception { int pos = 0; while(true) { int c = System.in.read(); switch (c) { case -1: System.out.println("Server Quits!!"); return; case '\r': break; /** n o w j a v a . c o m - 时 代 Java 提供 **/ case '\n': ds.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(),clientPort)); pos = 0; break; default: buffer[pos++] = (byte) c; } } } // UDP Client Method public static void TheClient() throws Exception { while (true) { DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); System.out.println(new String(p.getData(), 0, p.getLength())); } } public static void main(