发送端:
package cn.sasa.netDemo1; import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class SendDemo { public static void main(String[] args) throws IOException {
/**
* DatagramPacket 数据报包,用于封装数据
*
* DatagramSoket 用于数据传输
*
* 两者都用于发送和接收
*/ //实现UDP的发送
//1、创建DatagramPacket对象,封装数据、接收的地址和端口
//2、创建DatagramSocket
//3、调用DatagramSocket的send方法发送数据
//4、关闭资源,关闭DatagramSocket
//
byte[] buff = "hello".getBytes();
InetAddress host = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(buff, buff.length, host, 8046); DatagramSocket socket = new DatagramSocket();//发送使用空参构造函数
socket.send(packet);//调用send
socket.close();
} }
接收端:
package cn.sasa.netDemo1; import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket; public class ReceiveDemo { public static void main(String[] args) throws IOException {
/**
* UDP的接收端
*
* DatagramPacket 封装数据包,接收数据
*
* DatagramSocket 实现数据传输
*
* 接收步骤:
* 1、创建DatagramSocket,绑定端口号,与发送端的端口号保持一致
* 2、创建字节数组,接收数据
* 3、创建DatagramPacket
* 4、调用DatagramSocket的receive(DatagramPacket p)
* 接收数据放在数据包
* 5、拆包
* 发送端IP
* 接收到的字节长度
* 发送端端口号
* 6、关闭资源
*
*/
//DatagramPacket
DatagramSocket socket = new DatagramSocket(8046);
byte[] buff = new byte[1024];
DatagramPacket packet = new DatagramPacket(buff, buff.length);
socket.receive(packet);
int length = packet.getLength();//接收的字节长度
System.out.println(new String(buff,0,length));
System.out.println(packet.getAddress().getHostAddress()); //打印发送端IP地址
System.out.println(packet.getPort());
socket.close();
} }