为什么我的代码只发送大文件的一部分

时间:2014-09-28 23:54:10

标签: java networking

我试图制作一个Java套接字文件服务器,但我已经走到了死胡同,它似乎工作,直到在4080循环后似乎停止,任何想法为什么会发生这种情况?这是我的代码:

public class FileSender extends Thread{

private final int PORT = 7777;
private Socket sock;
private DataInputStream fileStream;
private OutputStream out;
private File file ;

public void run() { 

    try {
       file = new File("path");

       if(file.exists()){
           System.out.println("Found File");

           if(file.canRead()){
               System.out.println("Can Read File");
           }
       }
    this.fileStream = new DataInputStream(new FileInputStream(file));



        sock = new Socket("localhost",PORT);
        out = sock.getOutputStream();

        copyStream(fileStream, out, file);

    } catch (IOException ex) {
        Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public void copyStream(DataInputStream in, OutputStream out, File file) throws IOException{

    byte[] buf = new byte[1024];

    int total = 0;

    while(file.getTotalSpace() != total){
        int r = in.read(buf);


        if(r != -1){
        out.write(buf, 0, r);
        }

        total += r;
    }

    out.flush();

    System.out.println("Total was:" + total);

}

}

这是我的服务器:

public class FileReceiver extends Thread {

private final int PORT = 7777;
private ServerSocket sSoc;
private DataInputStream in;

public void run() {

    try {

        byte[] buf = new byte[1024];

        sSoc = new ServerSocket(PORT);

        Socket conn = sSoc.accept();

        in = new DataInputStream(new BufferedInputStream(conn.getInputStream()));

        File file = new File("C:\\test.rar");

        if (!file.exists()) {
            file.createNewFile();
        }

        if (file.canWrite()) {

            FileOutputStream fos = new FileOutputStream(file);

            int x= 0 ;
            do {

                in.read(buf);
                System.out.println(x + " : " + buf);

                fos.write(buf);
                x++;

            } while (in.read(buf) != -1);

            System.out.println("Complete");
        }

    } catch (IOException ex) {
        Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

编辑:程序将发送一个小文本文件,但onlky发送一个较大文件的一部分。

2 个答案:

答案 0 :(得分:0)

whilecopyStream循环中的条件似乎错了。请尝试将其更改为以下内容并尝试。

public void copyStream(DataInputStream in, OutputStream out, File file) throws IOException{

    byte[] buf = new byte[1024];

    int total = 0;

    while(true){
        int r = in.read(buf);    

        if(r != -1){
            out.write(buf, 0, r);
            total += r;
        } else {
            break;
        }  

    }

答案 1 :(得分:0)

问题出现在我的服务器中,我调用in.read()两次强制任何大于单个缓冲区大小的错过段。

相关问题