0

我正在尝试在 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 字节的数据,永远无法退出循环。

非常感谢凯夫

4

1 回答 1

1

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

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

阅读IO 教程

于 2012-11-30T20:23:43.807 回答