UDP(user datagram protocol):用户数据包传输协议。无连接服务。
Socket:效率低,每次都需要建立连接,耗费时间,安全性高
UDP:效率高,但不安全,容易造成数据丢失。
单播:一对一
组播:多对多
广播:一对多
发送方public static void main(String[] args) {
try {
// 定义发送信息
String str = "一个来自远方的快递!";
// 定义发送信息
DatagramSocket ds = new DatagramSocket();
// 打包快递
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
InetAddress.getByName("127.0.0.1"), 3838);
// 开始发送
ds.send(dp);
ds.close();
System.out.println("发送完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
接收方 public static void main(String[] args) {
try {
// 定义发送信息
String str = "一个来自远方的快递!";
// 定义发送信息
DatagramSocket ds = new DatagramSocket();
// 打包
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
InetAddress.getByName("127.0.0.1"), 3838);
// 开始发送
ds.send(dp);
ds.close();
System.out.println("发送完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
2. urdp发送图片// 定义数据包(null)
DatagramPacket dp = null;
// 定义要发送的文件对象
File file = new File("D:\图片\2024096.jpg");
// 定义字节读取流
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
// 开始读取
while (bis.read(bs) != -1) {
// 开始创建数据包
dp = new DatagramPacket(bs, bs.length),
InetAddress.getByName("127.0.0.1"),3838);



