概念
UDP 是User Datagram Protocol的简称, 中文名是用户数据包协议,是 OSI 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETF RFC 768是UDP的正式规范。
2.文件传输流程
在此使用UDP协议传送文件的程序中,先在服务器端设定监听端口号(3666),在接收客户端发来的请求之前一直处于阻塞状态;在客户端则从本地读取二进制文件并封装成数据报,并发送到相应的服务器端(ip:,端口:3666);当服务器端接收到客户端发来的请求后,则对数据进行处理,即读取并保存数据,然后返回操作后的信息到客户端;当客户端接收到服务器端的信息后,则输出服务器端返回的信息,到此时就完成了客户端的请求和服务器端的应答;最后关闭DatagramSocket。
3.程序流程图
服务器端 Socket() 客户端 Receive(Socket() readFile件发送文接收到来自客户端的数据 YsendTo() writeFil数据应Receive(sendTo() 显示返回的信息 Close()
4.程序部分源码
服务器端源码
public class Server extends Thread { DatagramSocket ds = null; DatagramPacket dp = null; File file = null;
}
@Override
public void run() { ;
DatagramPacket packet = new DatagramPacket(), (), (), 6666); ength); (); }
客户端源码
public class Client {
private DatagramSocket ds = null; private DatagramPacket dp = null; /**
* 传输文件
* @param filePath 文件所在路径 */
public void TransmitFile(String filePath) { try {
rim());
} catch (Exception e) { ();
} finally { (); }
}
/**
* 读取文件
}
*
* @param filePath * 文件路径 * @return
* @throws IOException */
public byte[] readFile(String filePath) throws IOException { File file = new File(filePath); if (!()) {
return null; }
InputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] data = new byte[1024]; int len = 0;
while ((len = (data)) != -1) { (data, 0, len); }
byte[] ret = (); return ret; }
5.运行结果截图
服务器端开启后
客户端启动后
UDP协议实现二进制文件传输(java)



