【问题标题】:Java while loop stack - blockedJava while 循环堆栈 - 阻塞
【发布时间】:2021-08-19 21:37:58
【问题描述】:

我正在尝试接收byte[] 中的文件,我正在使用:

byte[] buffer = new byte[16384]; // How many bytes to read each run

InputStream in = socket.getInputStream(); // Get the data (bytes)

while((count = in.read(buffer)) > 0) { // While there is more data, keep running
    fos.write(buffer); // Write the data to the file

    times++; // Get the amount of times the loop ran
    System.out.println("Times: " + times);
}

System.out.println("Loop ended");

循环在 1293 次后停止,然后停止打印时间。但是代码没有移动到System.out.println("Loop ended"); - 似乎循环正在等待什么......

为什么循环没有中断?

【问题讨论】:

  • in.read(buffer) 可能会停止代码,试图无限期地读取数据。
  • 也许吧。但我认为没有其他方法可以从输入流中读取数据

标签: java while-loop buffer


【解决方案1】:

您的循环仅在输入流的末尾终止。发送者是否终止了流(关闭了套接字)?如果没有,那还没有结束。

在这种情况下,read() 将pend until there is at least one byte

如果由于某种原因无法在文件末尾关闭套接字,那么您将需要找到另一种方法让接收者知道何时退出循环。通常的方法是先发送将要发送的字节数。


您的写入文件也有问题,因为它会尝试写入整个缓冲区。但是读取可以返回部分缓冲区;这就是它返回计数的原因。返回的计数需要用于写入输出文件。

【讨论】:

  • “发送方是否终止了流(关闭了套接字)?” - 是的
猜你喜欢
  • 2018-06-09
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
相关资源
最近更新 更多