简体   繁体   English

使用Java中的套接字将文件从服务器下载到客户端

[英]Download file from server to client using socket in java

I got some code to upload file from client to server and that working fine, the uploaded file saved in Server folder called Server, now would like to download file that exist in server folder to client folder but do not know how to do that. 我有一些代码可以将文件从客户端上传到服务器,并且工作正常,上传的文件保存在名为Server的Server文件夹中,现在想将服务器文件夹中存在的文件下载到Client文件夹,但是不知道该怎么做。 please give help 请帮忙

this server code illustrate downloading file from client to server: 此服务器代码说明了从客户端到服务器的下载文件:

  public static void downloadFile() throws Exception{
    try {
        fileEvent = (FileEvent) inputStream.readObject();
        if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
            System.out.println("Error occurred ..So exiting");
            System.exit(0);
        }
        String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
        if (!new File(fileEvent.getDestinationDirectory()).exists()) {
            new File(fileEvent.getDestinationDirectory()).mkdirs();
        }

        int filenamelength = dis.readInt();
        String filename = makeString(filenamelength, dis);

        dstFile = new File(path + filename);
        fileOutputStream = new FileOutputStream(dstFile);
        fileOutputStream.write(fileEvent.getFileData());
        fileOutputStream.flush();
        fileOutputStream.close();
        System.out.println("Output file : " + outputFile + " is successfully saved ");
        Thread.sleep(3000);
        System.exit(0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

and this is the client code to upload file from client to server: 这是用于将文件从客户端上传到服务器的客户端代码:

 public static void sendFile() throws Exception {
    dos.writeInt(6);
    dos.writeChars("upload");

    fileEvent = new FileEvent();
   String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
    String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
    fileEvent.setDestinationDirectory(destinationPath);
    fileEvent.setFilename(fileName);
    fileEvent.setSourceDirectory(sourceFilePath);
    File file = new File(sourceFilePath);
    if (file.isFile()) {
        try {
            DataInputStream diStream = new DataInputStream(new FileInputStream(file));
            long len = (int) file.length();
            byte[] fileBytes = new byte[(int) len];
            int read = 0;
            int numRead = 0;
            while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
                    fileBytes.length - read)) >= 0) {
                read = read + numRead;
            }
            fileEvent.setFileSize(len);
            fileEvent.setFileData(fileBytes);
            fileEvent.setStatus("Success");
        } catch (Exception e) {
            e.printStackTrace();
            fileEvent.setStatus("Error");
        }
    } else {
        System.out.println("path specified is not pointing to a file");
        fileEvent.setStatus("Error");
    }
    //Now writing the FileEvent object to socket
    try {

        outputStream.writeObject(fileEvent);

        System.out.println("Choose file: ");
        String str = scanner.nextLine();

        String[] parts = str.split(Pattern.quote("\\"));
        String filename = parts[parts.length - 1];

        dos.writeInt(filename.length());
        dos.writeChars(filename);

        Thread.sleep(3000);
        System.exit(0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}
  1. You don't state which API you're getting FileEvent from, but you shouldn't be using any technique like this that assumes the file will fit into memory: 您没有说明要从哪个API获取FileEvent ,但是您不应使用任何假设文件可以放入内存的技术:

     long len = (int) file.length(); byte[] fileBytes = new byte[(int) len]; 

    Here you're assuming (a) that len <= Integer.MAX_VALUE , and (b) that you can create a byte array of that size. 在这里,您假设(a) len <= Integer.MAX_VALUE和(b)您可以创建该大小的字节数组。 It doesn't scale. 它无法缩放。

      int read = 0; int numRead = 0; while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) { read = read + numRead; } fileEvent.setFileSize(len); fileEvent.setFileData(fileBytes); 

    Ditto. 同上。

  2. You shouldn't mix use of ObjectOutputStream and DataOutputStream on the same socket like this: 您不应像这样在同一套接字上混合使用ObjectOutputStreamDataOutputStream

     outputStream.writeObject(fileEvent); ... dos.writeInt(filename.length()); dos.writeChars(filename); 

So already it isn't going to work in the general case, whatever your tests may show. 因此,无论您的测试显示什么,它在一般情况下都行不通。

Instead you should either use an existing protocol like FTP, which you can use directly via a URL in the case of downloading, and via the Apache client in the case of uploading. 相反,您应该使用现有的协议(例如FTP),在下载的情况下可以直接通过URL使用,而在上传的情况下可以通过Apache客户端直接使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM