- 1
- 0
- 约1.3万字
- 约 9页
- 2019-10-24 发布于山西
- 举报
主要功能是:
1、TCP服务器提供文件下载服务,服务器支持多线程。
2、TCP?Client从服务器上下载指定的文件,Client也支持多线程。
首先是服务器,服务器是在PC机上,JAVA运行环境,主要参考网上的代码,自己做了支持多线程处理
//file:DownloadServer.java
import .*;
import java.io.*;
class ServerOneDownload extends Thread {
private Socket socket = null;
private String downloadRoot = null;
private static final int Buffer = 8 * 1024;
public ServerOneDownload(Socket socket, String downloadRoot) {
super();
this.socket = socket;
this.downloadRoot = downloadRoot;
start();
}
// 检查文件是否真实存在,核对下载密码,若文件不存在或密码错误,则返回-1,否则返回文件长度
// 此处只要密码不为空就认为是正确的
private long getFileLength(String fileName, String password) {
// 若文件名或密码为null,则返回-1
if ((fileName == null) || (password == null))
return -1;
// 若文件名或密码长度为0,则返回-1
if ((fileName.length() == 0) || (password.length() == 0))
return -1;
String filePath = downloadRoot + fileName; // 生成完整文件路径
System.out.println(DownloadServer getFileLength----- + filePath);
File file = new File(filePath);
// 若文件不存在,则返回-1
if (!file.exists())
return -1;
return file.length(); // 返回文件长度
}
// 用指定输出流发送指定文件
private void sendFile(DataOutputStream out, String fileName)
throws Exception {
String filePath = downloadRoot + fileName; // 生成完整文件路径
// 创建与该文件关联的文件输入流
FileInputStream in = new FileInputStream(filePath);
System.out.println(DownloadServer sendFile----- + filePath);
byte[] buf = new byte[Buffer];
int len;
// 反复读取该文件中的内容,直到读到的长度为-1
while ((len = in.read(buf)) = 0) {
out.write(buf, 0, len); // 将读到的数据,按读到的长度写入输出流
out.flush();
}
out.close();
in.close();
}
// 提供下载服务
public void download() throws IOException {
System.out.println(启动下载... );
您可能关注的文档
最近下载
- 八年级下册数学《平行四边形的判定》PPT教学课件 第2课时.pptx VIP
- 《GB/T 18336.1-2024网络安全技术 信息技术安全评估准则 第1部分:简介和一般模型》.pdf
- 党工委书记工作述职报告基层党组织书记述职报告季度月度年度工作汇报教育课件ppt模板.pptx VIP
- 一种活性茯苓多糖、其制备方法及应用.pdf VIP
- 柔性生产系统的设计、安装与调试.ppt VIP
- 绿色建筑施工专项方案.pdf
- 《神经重症气管切开患者气道功能康复与管理专家共识(2024)》解读PPT课件.pptx VIP
- 县城污水处理厂污泥处理处置服务项目招标文件.pdf
- 高校基层党组织书记抓党建工作述职.ppt VIP
- 2026年及未来5年市场数据中国高价HPV疫苗行业市场前景预测及投资价值评估分析报告.docx VIP
原创力文档

文档评论(0)