【问题标题】:java file receive stopsjava文件接收停止
【发布时间】:2014-10-27 11:43:49
【问题描述】:

我在 java 中使用 sockets 进行 文件传输。 这是客户端代码

for(int i = 0;i < fileList.size();i++) {
    String filename = (String)fileList.get(i);
    RequestFile(filename);

    try {
        BufferedOutputStream fileWriter = new BufferedOutputStream(
                                              new FileOutputStream(
                                                  new File(PROGRAM_PATH + "/" + 
                                                           filename)));         
        int packet;
        int count = 0;

        while((packet = fileReader.read()) != -1) {
            fileWriter.write(packet);
            count++;
        }

        System.out.println(filename + " receiver complete. (count : " + count + ")");
        fileWriter.flush();
        fileWriter.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是服务器代码

public void SendFile(String filename) {
    try {
        fileReader = new BufferedInputStream(new FileInputStream(CLIENT_PATH + "/" + filename));

        int packet;
        int count = 0;
        while((packet = fileReader.read()) != -1) {
            count++;
            fileWriter.write(packet);
        }
        fileWriter.write(-1);
        System.out.println(count);

        fileReader.close();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

当我检查服务器的计数时,它是635。这意味着服务器已发送数据635 次。 但是,客户的打印次数只有512。 (从 0 到 511)我认为它停在了read(),因为

System.out.println(filename + " receiver complete. (count : " + count + ")");

不打印。谁能告诉我原因和解决方法?

【问题讨论】:

  • 我认为您应该使用packet 增加count 并检查是否所有字节都被传输。

标签: java file-transfer bufferedinputstream bufferedoutputstream


【解决方案1】:

在服务器端,您不能向客户端发送值为-1 的字节。这一行:

fileWriter.write(-1);

它不会做你想做的事。 write() 方法将采用参数的最低 8 位并将其作为一个字节发送(在本例中为 0xff)。在客户端,fileReader.read() 将接收到 0xffint 类型)而不是 -1int 类型)。

-1 是一个特殊值,表示已到达流的末尾。它不是要写入或读取的有效数据。如果您发送-1,客户端会将其读取为0xff=255。可以发送和接收的值是0..255,包括两者。同样,-1 是流结束的特殊值。

在服务器端,您不会刷新或关闭输出流。这可能解释了差异(缓冲区中保存的数据可能无法传递给客户端)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    相关资源
    最近更新 更多