1.UPD分为:
单播:就是一对一传输
组播:就是多个人对多个人
广播:就是一对多
2.发送文件
public static void main(String[] args) {
try {
//定义发送信息的人
DatagramSocket ds=new DatagramSocket();
//定义字节数组
byte []bs=new byte[10];
//定义空数据包
DatagramPacket dp=null;
//定义要发送文件的对象
File file=new File("D:\\李诗渊\\上海.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"),6969);
//开始发送
ds.send(dp);
}
//文件发送完成后,在额外发送一个数据包
dp=new DatagramPacket("拜拜".getBytes(), "拜拜".getBytes().length,InetAddress.getByName("127.0.0.1"),6969);
//开始发送
ds.send(dp);
//关闭
ds.close();
bis.close();
System.out.println("发送完成");
} catch (Exception e) {
e.printStackTrace();
}
}
3.接收文件
public static void main(String[] args) {
try {
System.out.println("等待发送");
// 定义接受信息的人
DatagramSocket ds = new DatagramSocket(6969);
// 定义接受数据包
DatagramPacket dp = null;
// 定义接受的字节数据、
byte[] bs = new byte[10];
// 定义保存的文件路径
File file = new File("D:\\月");
// 定义字节写入流
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();
}
}