UDP(user datagram protocol)

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();
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值