Junjiejkl 发表于 2013-1-15 08:12:20

最简单的UDP编程

接收端:
import java.io.*;import java.net.*;public class TestUDPServer {public static void main(String[] args) throws Exception{byte[] buf = new byte;DatagramPacket dp = new DatagramPacket(buf, buf.length);DatagramSocket ds = new DatagramSocket(5678);while(true){ds.receive(dp);ByteArrayInputStream bis = new ByteArrayInputStream(buf);DataInputStream dis = new DataInputStream(bis);System.out.println(dis.readLong());}}}  
发送端:
import java.io.*;import java.net.*;public class TestUDPClient{public static void main(String[] args) throws Exception{long n = 10000L;ByteArrayOutputStream bos = new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream(bos);dos.writeLong(n);byte[] buf = bos.toByteArray();DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));DatagramSocket ds = new DatagramSocket(9999);ds.send(dp);ds.close();}} 
 
页: [1]
查看完整版本: 最简单的UDP编程