【问题标题】:Sockets transferring less than entire file [duplicate]传输少于整个文件的套接字[重复]
【发布时间】:2013-06-26 07:04:33
【问题描述】:

我正在尝试使用 Java 中的套接字发送文件。问题是这样的: 假设有一个 97kb 的文件。它得到大约 95.8kb 并等待更多,但作者已发送所有 97kb。

阅读:

FileOutputStream fout = new FileOutputStream(fl);
int counter = 0;
byte[] byt = new byte[8192];
BufferedInputStream bin = new BufferedInputStream(cli.InputStream());
int count = 0;

while((count = bin.read(byt)) > 0)
{
    counter = counter + count;
    Log.d("TINTERACT", String.valueOf(count) + " _" + String.valueOf(counter) + " _" +  String.valueOf(size));
    fout.write(byt, 0, count);
}

fout.flush();
fout.close();

写作时是:

System.out.println("Starting writing");
FileInputStream fIn = new FileInputStream(path);
byte[] byt = new byte[8192];
BufferedInputStream bin = new BufferedInputStream(fIn);
BufferedOutputStream bout = new BufferedOutputStream(ser.OutputStream());

int count = 0, countr = 0;
while((count = bin.read(byt)) > 0)
{
    System.out.println(count);
    bout.write(byt, 0, count);
    countr = countr + count;
}

bout.flush();
System.out.println("sent " + countr + "End");
bin.close();

writer 完成发送字节总数,而 reader 没有获取所有字节并循环等待它

【问题讨论】:

  • 能否指出我代码中的错误。
  • ...您可以尝试在不使用BufferedInputStream 的情况下直接使用cli.InputStream()
  • 幽默一下 - 你是否知道一个事实,例如通过检查数据,文件的尾部还没有到达?只是为了排除 K=1024 与 K=1000 之间的差异,或实际大小与所需磁盘块等的差异。
  • @Selvin 他当然可以,但为什么呢?不会有任何区别。
  • 关闭你的写入怎么样?我看到你打电话给bout.flush(),但从来没有打电话给bout.close()

标签: java android sockets


【解决方案1】:

尝试使用:

while((count = bin.read(byt)) != -1)

代替:

while((count = bin.read(byt))>0)

【讨论】:

  • 对于 FSM 而言,差异在哪里?如果有 EOF bin.read(byt) 将返回 -1 所以(count = bin.read(byt))>0(count = bin.read(byt)) != -1 都将返回 false
  • 我试过放 -1 ,但还是同样的问题。
  • @shankhan:前者不适用于0
  • @Selvin 从标题我们可以假设 InputStream 最终来自网络套接字。与文件不同,如果连接保持未中断,您将不会在套接字上获得 eof,因为只要它仍然连接,现在没有更多可用数据的事实并不一定意味着不会有任何数据将来会提供更多。
  • @ChrisStratton ...您的评论甚至更好地解释了为什么这个答案应该被否决...(count = bin.read(byt)) != -1在连接关闭之前不会是false(在套接字流上)...
【解决方案2】:

在发送者关闭他的套接字之前,从套接字读取的接收器循环不会终止。

【讨论】:

  • 是的,它可以工作,但我不想关闭流,因为应用程序是文件管理器,并且使用可能需要更多套接字在此文件发送后发送文件
  • 所以循环到 EOS 是行不通的,不是吗?您必须在文件之前发送文件的长度并循环,直到您读取了那么多字节。
  • 请看下面我的解决方案,并请解释为什么它会在没有关闭套接字的情况下发生
猜你喜欢
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 2015-03-06
  • 2012-04-29
相关资源
最近更新 更多