Java UDP 数据传输

DatagramPacket:UDP数据包

DatagramSocket:UDP Socket

// 发送数据
byte[] message = "Hello, UDP".getBytes(); // 发送的数据
InetAddress address = InetAddress.getByName("192.168.1.1"); // 接收主机IP
int portNum = 11024; // 接收端口号
DatagramSocket sendSocket = new DatagramSocket(); // UDP Socket
DatagramPacket data = new DatagramPacket(message, message.length, address, portNum); // 数据包
sendSocket.send(data); // 发送数据
// 接收数据
byte[] receiveBuf = new byte[1024]; // 接收缓存空间
int portNum = 11024; // 接收端口号
DatagramPacket data = new DatagramPacket(receiveBuf, receiveBuf.length); // 接收数据存放包
DatagramSocket receiveSocket = new DatagramSocket(portNum);
receiveSocket.receive(data);
/*
 * receiveBuf就是接收到的数据Buf 
 */

 

 

posted on 2013-10-15 10:05  麥籽  阅读(338)  评论(0编辑  收藏  举报