import java.net.*; import java.io.*; public class TestUDPServer { public static void main(String[] args) throws Exception { byte [] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); DatagramSocket ds = new DatagramSocket(5678); ByteArrayInputStream bais = new ByteArrayInputStream(buf); while(true) { DataInputStream dis = new DataInputStream(bais); ds.receive(dp);//阻塞式的 //System.out.println(new String(buf, 0, dp.getLength())); System.out.println(dis.readLong()); } } }
import java.net.*; import java.io.*; public class TestUDPClient { public static void main(String[] args) throws Exception{ //向服务器端传一个long类型数字 long n = 10000; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(n); byte [] buf = baos.toByteArray(); //byte [] buf = (new String("hello")).getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1",5678)); DatagramSocket ds = new DatagramSocket(9999); ds.send(dp); ds.close(); } }