Java:客户端/服务器文件传输(不完整的文件)

时间:2015-01-14 15:33:04

标签: java multithreading file-transfer serversocket

我正在构建一个通过套接字在网络上发送文件的应用程序。

有2个节目。服务器和客户端每个都有两个类下载和上传。

 public class Download implements Runnable{

        public ServerSocket server;
        public Socket socket;
        public int port;
        public String saveTo = "";
        public InputStream In;
        public FileOutputStream Out;

        public Download(String saveTo){
            try {
                server = new ServerSocket(1544);
                port = 1544;
                this.saveTo = saveTo;            
            } 
            catch (IOException ex) {
                System.out.println("Exception [Download : Download(...)]");
            }
        }

        @Override
        public void run() {
            try {
                socket = server.accept();
                In = socket.getInputStream();
                Out = new FileOutputStream(saveTo);
                byte[] buffer = new byte[1024];
                int count;
                while((count = In.read(buffer)) >= 0){
                    Out.write(buffer, 0, count);
                }
                Out.flush();
                if(Out != null){ Out.close(); }
                if(In != null){ In.close(); }
                if(socket != null){ socket.close(); }
            } 
            catch (Exception ex) {

                ex.printStackTrace();
            }
        }
    }

和类上传:

public class Upload implements Runnable{
    public String addr;
    public int port;
    public Socket socket;
    public FileInputStream In;
    public OutputStream Out;
    public File file;
    public Upload(String addr, int port, File filepath){
        super();
        try {
            file = filepath;
            socket = new Socket("127.0.0.1",1545);
            Out = socket.getOutputStream();
            In = new FileInputStream(filepath);
        } 
        catch (Exception ex) {
            System.out.println("Exception [Upload : Upload(...)]");
        }
    }
    @Override
    public void run() {
        try {       
            byte[] buffer = new byte[1024];
            int count;

            while((count = In.read(buffer)) >= 0){
                Out.write(buffer, 0, count);
            }
            Out.flush();
           if(In != null){ In.close(); }
            if(Out != null){ Out.close(); }
            if(socket != null){ socket.close(); }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

在班级服务器中:

 File myFile = new File("temp");
 Upload upl = new Upload("temp", 1544,myFile)
 fileThreadSend = new Thread(upl);
 fileThreadSend.start();

并在班级客户端:

 Download dwn = new Download("temp");
 Thread fileThread = new Thread(dwn);
 fileThread.start();

问题仍然存在,但它不会传输所有文件 有时它只传输9kb,有时甚至20 MBS。 怎么了? 我试图搜索但找不到适用的任何解决方案。 提前致谢

1 个答案:

答案 0 :(得分:0)

不要打扰并使用JDK提供的功能:

更多详情here。并且不要忘记使用try-with-resources。

另外,请避免直接使用Thread并改为使用ExecutorService