文件传输服务器<->客户端,文件不完整

时间:2019-11-28 17:58:44

标签: java sockets fileinputstream fileoutputstream

说明

该应用程序假定将文件形式传输到服务器,并且应从命令行运行。 -d参数用于下载,-u参数用于从服务器上传/向服务器上传。

问题

主要问题是,在启动服务器应用程序后,第一个请求始终“被处理”。

  • 用于上传的文件开头丢失
  • 下载进度百分比全错

1

仅在服务器启动后的第一个请求发生,此后的所有其他请求都很好。

代码

  • 服务器

主要

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    public static void main(String[]  args){
        new Main();
    }

    private Main(){
        ServerSocket servSoc = null;
        try {
            servSoc = new ServerSocket(4400);
        } catch (IOException e) {
            System.out.println("Failed to start the server");
            e.printStackTrace();
            System.out.println("Closing the server...");
            System.exit(0);
        }

        System.out.println("Server running");
        System.out.println("Awaiting connections...");
        System.out.println("---------------");
        while(true){
            try {
                Socket clientSocket = servSoc.accept();
                new Connection(clientSocket).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

连接

//Jaroslaw Janas
//17436176

import java.io.*;
import java.lang.reflect.Field;
import java.net.Socket;

public class Connection extends Thread {

    private Socket soc;
    Connection(Socket soc){
        this.soc = soc;
    }

    @Override
    public void run(){
//        <<<<<<<<<<<<<<<<<<<< SETUP >>>>>>>>>>>>>>>>>>>>
        String str = "Received a connection from: "
                + soc.getRemoteSocketAddress().toString();
        System.out.println(str);

//        Get arguments
        String operation = null;
        String filename = null;

        BufferedReader br = null;
        try {
            br= new BufferedReader(new InputStreamReader(soc.getInputStream()));
            operation = br.readLine();
            filename = br.readLine();


        } catch (IOException e) {
            System.out.println("Failed to initialize BufferedReader");
            e.printStackTrace();
            System.out.println("Closing the server...");
            System.exit(0);
        }

//        <<<<<<<<<<<<<<<<<<<< UPLOAD>>>>>>>>>>>>>>>>>>>>

//        Upload from client
        if(operation.equalsIgnoreCase("u")){
            System.out.println("Upload request for" + filename);

//            Create new file
            File f = new File("files/"+filename);

//            Set up FileInputStream
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(f);
            } catch (FileNotFoundException e) {
                System.out.println("Failed to set up the FileOutputStream");
                e.printStackTrace();
            }

            System.out.println("Receiving the file from " + soc.getRemoteSocketAddress().toString());
//            Set up the InputStream for receiving the file
            InputStream is = null;
            try {
                assert fos != null;
                is = soc.getInputStream();

                byte[] bytes = new byte[8*1024];
                int count;
                while ((count = is.read(bytes)) > 0) {
                    fos.write(bytes, 0, count);
                }

                System.out.println("File " + filename + " received");
                is.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

//        <<<<<<<<<<<<<<<<<<<< DOWNLOAD >>>>>>>>>>>>>>>>>>>>

//        Download from client
        else if(operation.equalsIgnoreCase("d")){
            System.out.println("Download request for " + filename);

//        set up the the stream
        PrintStream ps = null;
        try {
            ps = new PrintStream(soc.getOutputStream());
        } catch (IOException e) {
            System.out.println("Failed to configure the PrintStream");
            e.printStackTrace();
        }

//        read the file
            File f = new File("files/"+filename);
            FileInputStream fip = null;
            try {
                fip = new FileInputStream(f);
            } catch (FileNotFoundException e) {
                System.out.println("Did not find the file");
                e.printStackTrace();
            }

            System.out.println("Sending the file to " + soc.getRemoteSocketAddress().toString());
//        Send the file
            try {
                assert fip != null;

                byte[] bytes = new byte[8*1024];
                int count;
                while ((count = fip.read(bytes)) > 0) {
                    assert ps != null;
                    ps.write(bytes, 0, count);
                }

                System.out.println("File " + filename + " sent");
            } catch (IOException e) {
                System.out.println("Failed to read the file");
                e.printStackTrace();
            }

//        close stuff
            assert ps != null;
            ps.flush();
            ps.close();
        }
        else{
            System.out.println("Incorrect request");
        }

//        <<<<<<<<<<<<<<<<<<<< CLOSE CONNECTION >>>>>>>>>>>>>>>>>>>>
        try {
            br.close();
            soc.close();
            System.out.println("Connection " + soc.getRemoteSocketAddress().toString() + " closed");
            System.out.println("---------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  • 客户

主要

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.net.Socket;

public class Main {

    public static void main (String[] args){
        new Main(args);
    }

    private Main(String[] args){
        int port;
        String ip, operation, filePath;

        ip = args[0];
        port = Integer.parseInt(args[1]);
        operation = args[2];
        filePath = args[3];

        System.out.println(ip + " " + port + " " + operation + " " + filePath);

        Socket soc;
        try {
            System.out.println("Connecting to the server...");
            soc = new Socket(ip, port);
        } catch (IOException e) {
            System.out.println("Could not connect to the server");
            e.printStackTrace();
            System.out.println("Stopping the client");
            return;
        }

        System.out.println("Connected to " + soc.getRemoteSocketAddress().toString());

        if(operation.equalsIgnoreCase("-u")){
            System.out.println("Configuring the upload");
            new Upload(soc, filePath);
        }
        else if(operation.equalsIgnoreCase("-d")){
            System.out.println("Configuring the download");
            new Download(soc, filePath);
        }
        else{
            System.out.println("Invalid argument " +operation);
        }
    }
}

连接

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

abstract class Connection {

    private Socket soc;
    PrintStream ps;
    String filename;

    Connection(Socket soc, String filePath, String operation){
        this.soc = soc;
        filename = getFilePathFileName(filePath);

//        set up the the stream used for sending arguments
        try {
            ps = new PrintStream(soc.getOutputStream());
        } catch (IOException e) {
            System.out.println("Failed to configure the connection");
            e.printStackTrace();
        }

//        send arguments
        ps.println(operation);
        ps.println(filename);
    }

    private String getFilePathFileName(String filepath){
        String[] str = filepath.split("/");
        return str[str.length-1];
    }

    public void connectionClose(){
        ps.flush();
        ps.close();

        try {
            soc.close();
            System.out.println("Connection closed");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上传

//Jaroslaw Janas
//17436176

import java.io.*;
import java.net.Socket;

class Upload extends Connection {

    Upload(Socket soc, String filePath) {
        super(soc, filePath, "u");

//        Read the file
        File f = new File(filePath);
        FileInputStream fip = null;
        try {
            fip = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            System.out.println("Did not find the file");
            e.printStackTrace();
            System.out.println("Closing the client");
            System.exit(0);
        }

//        Send the file to the server
        try {
            System.out.println("Uploading...");

            byte[] bytes = new byte[8 * 1024];
            float fileSize = fip.available();

            int progress = 0;
            int count;
            while ((count = fip.read(bytes)) > 0) {
                ps.write(bytes, 0, count);

                progress += (count / fileSize) * 100;
                System.out.println(progress + "%");

            }

            System.out.println("Upload completed");
        } catch (IOException e) {
            System.out.println("Failed to upload " + filename);
            e.printStackTrace();
        }

//        Close the connection
        connectionClose();
    }
}

下载

//Jaroslaw Janas
//17436176

import java.io.*;
import java.net.Socket;

class Download extends Connection{

    Download(Socket soc, String filePath){
        super(soc, filePath, "d");

//        Create a new file
        File f = new File("files/"+filename);

//        Set up FileOutputStream - outputs to the file
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            System.out.println("Failed to set up the FileOutputStream");
            e.printStackTrace();
        }

//        Download the file
        InputStream is;
        try {
            assert fos != null;

            System.out.println("Downloading...");

//            Set up the InputStream for downloading the file
//            from the server
            is = soc.getInputStream();

            byte[] bytes = new byte[8*1024];
            float fileSize = is.available();

            int progress=0;
            int count;
            while ((count = is.read(bytes)) > 0) {
                fos.write(bytes, 0, count);

                progress += (count/fileSize) * 100;
                System.out.println(progress +"%");
            }

            System.out.println("File " + filename + " downloaded");
            is.close();
            fos.close();
        } catch (IOException e) {
            System.out.println("Failed to download " + filename);
            e.printStackTrace();
        }

//        Close the connection
        connectionClose();
    }
}

1 个答案:

答案 0 :(得分:0)

解决了。 是我与dis = new DataInputStream()一起使用dis.readLine()的BufferReader

对于下载,它是完全无关的。我试图获取从服务器发送到客户端的文件的文件大小。由于尚未发送文件,该命令返回0。我通过在发送实际文件之前发送文件的大小来修复它。

服务器

连接

//        <<<<<<<<<<<<<<<<<<<< SETUP >>>>>>>>>>>>>>>>>>>>
        String str = "Received a connection from: "
                + soc.getRemoteSocketAddress().toString();
        System.out.println(str);

//        Get arguments
        String operation = null;
        String filename = null;

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(soc.getInputStream());
            operation = dis.readLine();
            filename = dis.readLine();

        } catch (IOException e) {
            System.out.println("Failed to initialize the DataInputStream");
            e.printStackTrace();
        }

...

//        Send the file
            try {
                assert fip != null;

                ps.println(fip.available());
                byte[] bytes = new byte[8*1024];
                int count;
                while ((count = fip.read(bytes)) > 0) {
                    ps.write(bytes, 0, count);
                }
                fip.close();

                System.out.println("File " + filename + " sent");
            } catch (IOException e) {
                System.out.println("Failed to read the file");
                e.printStackTrace();
            }

客户

下载

//        Download the file
        DataInputStream dis;
        try {
            assert fos != null;

            System.out.println("Downloading "+filename);

//            Set up the DataInputStream for downloading the file
//            from the server
            dis = new DataInputStream(soc.getInputStream());

            byte[] bytes = new byte[8*1024];
            float fileSize = Float.parseFloat(dis.readLine());

            int progress=0;
            int count;
            while ((count = dis.read(bytes)) > 0) {
                fos.write(bytes, 0, count);

                progress += (count/fileSize) * 100;
                System.out.println(progress +"%");
            }

            System.out.println("File " + filename + " downloaded");
            dis.close();
            fos.close();
        } catch (IOException e) {
            System.out.println("Failed to download " + filename);
            e.printStackTrace();
        }