TCP Client从服务器上下载指定的文件.docVIP

  • 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(启动下载... );

文档评论(0)

1亿VIP精品文档

相关文档