文件下载服务器与客户端实现

该博客详细介绍了如何使用Java实现一个简单的文件下载服务器和客户端。服务器端通过ServerSocket监听并接受客户端请求,获取文件列表,发送文件信息,然后发送文件内容。客户端则接收服务器的文件列表,选择文件,指定保存目录,最后接收并保存文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器端代码:

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class DownloadServer {
 private ServerSocket ss;
 File dir = new File("f:/mv");
 public DownloadServer(int port)throws Exception{
  ss = new ServerSocket(port);
  new Thread(){
   public void run(){
    try {
     while(true){
      Socket s = ss.accept();
      //s交给通信线程
      TongxinThread tx = new TongxinThread(s);
      tx.start();
     }
    } catch (Exception e) {
     e.printStackTrace();
     System.out.println("服务器已经停止");
    }
   }
  }.start();
 }
 class TongxinThread extends Thread{
  Socket s;
  public TongxinThread(Socket s){
   this.s = s;
  }
  public void run(){
   //1.获得目录下文件列表
   //2发送列表
   //3收取文件号
   //4发送文件大小
   //5发送文件名
   //6发送文件
   try {
    while(true){
     File[] ary = listFiles();
     sendFileList(ary);
     int n = receiveFileNumber();
     sendFileList(ary[n-1].length());
     sendFileName(ary[n-1].getName());
     sendFile(ary[n-1]);
     if(!sendSuccess())
      break;
    }
   } catch (Exception e) {
    e.printStackTrace();
    System.out.println("传送文件失败。。。。");
   }
  }
  private boolean sendSuccess() throws Exception{
   DataInputStream in = new DataInputStream(s.getInputStream());
   boolean b = in.readBoolean();
   System.out.println(b);
   return b;
  }
  private void sendFile(File file) throws Exception{
   BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
   OutputStream out = s.getOutputStream();
   byte[] ary = new byte[8192];
   int n;
   while((n=fileIn.read(ary))!=-1){
    out.write(ary, 0, n);
   }
   fileIn.close();//文件流关闭
   out.flush();//刷出网络流,不能关闭网络流
  }
  private void sendFileName(String name) throws Exception{
   DataOutputStream out = new DataOutputStream(s.getOutputStream());
   out.writeUTF(name);
   out.flush();
  }
  private void sendFileList(long length) throws Exception{
   DataOutputStream out = new DataOutputStream(s.getOutputStream());
   out.writeLong(length);
   out.flush();
  }
  private int receiveFileNumber() throws Exception{
   DataInputStream in = new DataInputStream(s.getInputStream());
   int n = in.readInt();
   return n;
  }
  private void sendFileList(File[] ary) throws Exception{
   String[] names = new String[ary.length];
   for(int i=0;i<ary.length;i++){
    names[i] = ary[i].getName();
   }
   ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
   out.writeObject(names);
   out.flush();
//   System.out.println("Server-----sendFileList()");
  }
  private File[] listFiles() {
   File[] files = dir.listFiles(new FileFilter() {
    public boolean accept(File file) {
     return file.isFile();
    }
   });
   return files;
  }
 }
 public static void main(String[] args)throws Exception {
  DownloadServer server = new DownloadServer(8000);
  System.out.println("下载服务器已启动");
 }
}//DownloadServer

 

客户端代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/*
 * 下载客户端
 */
public class DownloadClient {
 private Socket s;
 private String defaultDir = "d:/download";
 private Scanner sc = new Scanner(System.in);
 public DownloadClient(String ip,int port)throws Exception {
  s = new Socket(ip,port);//创建Socket连接
 }
 public void start(){
  try {
   while(true){
    //1接收文件列表,并显示
    String[] ary = receiveFileList();
    printList(ary);
    //2输入文件号
    int n = inputFileNumber();
    //3输入目录
    String dir = inputDir();
    //4发送文件号
    sendFileNumber(n);
    //5接收文件
    //*收文件大小
    long length = receiveLength();
    //*收文件名
    String name = receiveName();
    //*收文件,并存入指定目录
    receiveAndSaveFile(new File(dir,name),length);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 private void receiveAndSaveFile(File file, long length) throws Exception{
  BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
  BufferedInputStream in = new BufferedInputStream(s.getInputStream());
  int b;
  long n=0;
  while((b=in.read())!=-1){
   fileOut.write(b);
   if(++n>=length){
    break;
   }
  }
  fileOut.flush();
  fileOut.close();
  System.out.println(file.getName() + " 文件下载成功。。");
  DataOutputStream out = new DataOutputStream(s.getOutputStream());
  out.writeBoolean(true);
 }
 private String receiveName() throws Exception{
  DataInputStream in = new DataInputStream(s.getInputStream());
  String name = in.readUTF();
  return name;
 }
 private long receiveLength() throws Exception{
  DataInputStream in = new DataInputStream(s.getInputStream());
  long length = in.readLong();
  return length;
 }
 private void sendFileNumber(int n) throws Exception{
  DataOutputStream out = new DataOutputStream(s.getOutputStream());
  out.writeInt(n);
  out.flush();
 }
 private String inputDir() {
  System.out.print("请输入存放的目录(回车结束):");
  String dir = sc.nextLine();
  if(dir.length()==0 || !(new File(dir).isDirectory())){
   return defaultDir;
  }
  return dir;
 }
 private int inputFileNumber() {
  System.out.print("请输入要下载的文件序号(回车结束):");
  String input = sc.nextLine();
  int n = Integer.parseInt(input);
  return n;
 }
 private void printList(String[] ary) {
  System.out.println("文件列表");
  System.out.println("---------------------------------");
  for(int i = 0;i<ary.length;i++){
   System.out.println((i+1) + ". " + ary[i]);
  }
  System.out.println("------------------------------------");
 }
 private String[] receiveFileList() throws Exception{
  ObjectInputStream in = new ObjectInputStream(s.getInputStream());
  String[] fileList = (String[]) in.readObject();
  return fileList;
 }
 public static void main(String[] args)throws Exception{
//  DownloadClient client = new DownloadClient("192.168.99.62", 8000);
  DownloadClient client = new DownloadClient("localhost", 8000);
  client.start();
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值