读书人

最简略的UDP编程

发布时间: 2012-12-22 12:05:06 作者: rapoo

最简单的UDP编程

接收端:

import java.io.*;import java.net.*;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);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();}}

?

?

读书人网 >编程

热点推荐