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

标签 java swing network-programming thread-safety swingworker

我正在尝试在2个Java套接字客户端之间构建文件传输机制。发送方客户端将包含以下代码片段:

    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”,现在的问题是服务器端获取的数据略少,而客户端B继续从服务器读取8192字节的数据,并且永远无法跳出循环。

非常感谢 凯夫

最佳答案

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

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

阅读the IO tutorial .

关于java - 为什么客户端B没有得到完整的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13650574/

相关文章:

java - 夏令时在Java中

java - 在同一台机器上设置多个 ActiveMQ 代理时出错

java - 使用Java程序设置/创建环境变量,该变量在Linux中执行程序后仍然存在

java - Android从 Assets 文件夹共享音频文件

java - 如何在 Mac OS 上使用 Java 创建一个类似 Combobox 的简单外观

java - 创建基于 GUI 的计时器(或秒表)

java - 何时使用 EventListenerList 而不是一般的监听器集合

go net conn.SetWriteDeadline函数用法

c# - 在.Net中设计 "Scalable Multi Threaded Socket Push Server"

jakarta-ee - 什么是网络中的骨架?