UDP(user datagram protocol):用户数据包传输协议,无连接服务
UDP和Socket的区别
Socket:效率低,每次都需要建立连接,耗费时间,安全性高
UDP:效率高,但是不安全,容易造成数据丢失
UDP分为:
单播:就是一对一传输
组播:就是多个人对多个人
广播:就是一对多
使用UDP发送信息:
发送方:
try {
// 定义要发送的信息/快递
String str = “发送信息的内容”;
// 定义发送信息的快递员
DatagramSocket ds = new DatagramSocket();
// 打包快递/定义数据包
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.getBytes().length,InetAddress.getByName(“127.0.0.1”),6666);
// 开始发送
ds.send(dp);
ds.close();//快递发送完后关闭
System.out.println(“发送完成”);
} catch (Exception e) {
e.printStackTrace();
}
接收方:
try {
// 定义接受信息的人
DatagramSocket ds = new DatagramSocket();
// 定义byte数组来接受信息
byte[] bs = new byte[60];
// 定义接受 信息的数据包
DatagramPacket dp = new DatagramPacket(bs, bs.length);
// 开始接受
ds.receive(dp);
// 将接受的字节数组转换成字符串
String str = new String(bs);
System.out.println(“接受的信息”+str.trim());
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
使用UDP发送文件:
发送方:
try {
// 发送信息的人
DatagramSocket ds = new DatagramSocket();
// 定义字节数组
byte[] bs = new byte[100];
// 定义数据包
DatagramPacket dp = null;
// 定义要发送的文件对象
File file = new File(“要发送的内容”);
// 定义字节读取流
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”),6666);
// 开始发送
ds.send(dp);
}
//文件发送完成后,在额外发送一个数据包(结束包)
dp=new DatagramPacket(“再见”.getBytes(), “再见”.getBytes().length,
InetAddress.getByName(“127.0.0.1”),6666);
//开始发送
ds.send(dp);
//关闭
ds.close();
bis.close();
System.out.println(“发送完成”);
} catch (Exception e) {
e.printStackTrace();
}
接收方:
try {
// 发送信息的人
DatagramSocket ds = new DatagramSocket(6666);
// 定义数据包
DatagramPacket dp = null;
// 定义接受的字节数组
byte[] bs = new byte[20];
// 定义保存的文件路径
File file = new File(“接收后要保存的路径”);
// 定义字节写入流
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 开始接受
while (true) {
// 创建接受的数据包
dp = new DatagramPacket(bs, bs.length);
// 开始接受
ds.receive(dp);
// 把每次接受的字杰数组转换成字符串
String str = new String(bs);
if (str.contains(“再见”)) {
break;
}
// 保存到本地
bos.write(bs);
bos.flush();
}
ds.close();
bos.close();
System.out.println(“接收完成”);
} catch (Exception e) {
e.printStackTrace();
}