为什么客户B没有得到完整的文件

时间:2012-11-30 17:58:18

标签: java swing network-programming thread-safety swingworker

我正在尝试在2个Java套接字客户端之间构建文件传输机制。发件人客户端将包含此sorta片段:

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    BufferedOutputStream outStream = null;
    byte[] fileBytes = new byte[(int) file.length()];
    int bytesRead = 0;

    try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        outStream = new BufferedOutputStream(socket.getOutputStream());
        bytesRead = bis.read(fileBytes, 0, fileBytes.length);
        outStream.write(fileBytes, 0, fileBytes.length);

    } catch (IOException _IOExc) {
        Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, 
            null, _IOExc);
        //QuitConnection(QUIT_TYPE_DEFAULT);
    } 

服务器介体如下所示:

public void run() {
    assert (outSocket != null);
    byte[] bytes = new byte[fileSize];
    try {
        System.out.println("inStream " + inStream.available());
        outStream = new BufferedOutputStream(outSocket.getOutputStream());
        inStream.read(bytes, 0, fileSize);
        outStream.write(bytes, 0, fileSize);
        outStream.flush();

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

目标客户端:

    public void run() {
        try {
            System.out.println("Start reading...");
            int len = 1024;
            BufferedInputStream inStream = new BufferedInputStream 
                  (client.user.getClientSocket().getInputStream());
            while ((bytesRead = inStream.read(fileBytes, 0, len)) > 
                  0 && current < fileSize) {
                current = current + bytesRead;
                System.out.println("current "+ current);
                bos.write(fileBytes, 0, bytesRead < len ? bytesRead : len);
            }
            bos.flush();
            bos.close();
        } catch (IOException ex) {
            Logger.getLogger(ReadFileThread.class.getName()).log(Level.SEVERE, 
                null, ex);
        } catch (InterruptedException e) {
        }
    }

服务器和目标客户端都提前传递“fileSize”,现在的问题是服务器端获得的数据量略少,而clientB只能从服务器读取8192个字节的数据,并且永远不会出现循环。

非常感谢 千电子伏

1 个答案:

答案 0 :(得分:1)

不要忽略read()方法的结果。它返回已读取的字节数,不一定是文件的长度。必须始终在循环中调用read(),直到它返回-1。

并且不要使用available()。它不会返回您认为它返回的内容。只需循环直到read()返回-1或直到读取的字节数达到预期的数量。

阅读the IO tutorial