【发布时间】:2015-07-18 17:21:21
【问题描述】:
我正在尝试使用 TCP 将文本文件传输到另一台服务器,但它的行为与预期不同。发送数据的代码是:
System.out.println("sending file name...");
String outputFileNameWithDelimiter = outputFileName + "\r\n"; //These 4 lines send the fileName with the delimiter
byte[] fileNameData = outputFileNameWithDelimiter.getBytes("US-ASCII");
outToCompression.write(fileNameData, 0, fileNameData.length);
outToCompression.flush();
System.out.println("sending content...");
System.out.println(new String(buffer, dataBegin, dataEnd-dataBegin));
outToCompression.write(buffer, dataBegin, dataEnd-dataBegin); //send the content
outToCompression.flush();
System.out.println("sending magic String...");
byte[] magicStringData = "--------MagicStringCSE283Miami".getBytes("US-ASCII"); //sends the magic string to tell Compression server the data being sent is done
outToCompression.write(magicStringData, 0, magicStringData.length);
outToCompression.flush();
因为这是 TCP 并且您不能像在 UDP 中那样发送离散的数据包,所以我希望所有数据都在输入流中,我可以使用分隔符来分隔文件名、内容和结束字符串,然后每个 in.read() 只会给我下一个后续的数据量。
相反,这是我每次读取时获得的数据:
On the first in.read() byteBuffer appears to only have "fileName\r\n".
On the second in.read() byteBuffer still has the same information.
On the third in.read() byteBuffer now holds the content I sent.
On the fourth in.read() byteBuffer holds the content I sent minus a few letters.
On the fifth in.read() I get the magicString + part of the message.
我在每次从 Web 服务器发送时都会刷新,但输入流似乎无法实现可刷新。
谁能解释为什么会这样?
编辑: 这就是我读取内容的方式。基本上这是循环然后写入文件。
in.read(byteBuffer, 0, BUFSIZE);
【问题讨论】:
-
您能在客户端显示您是如何从
in读取数据的吗?我强烈怀疑您没有检查in.read()的返回值(实际从流中读取的字节数)。 -
我不是,但为什么要检查这件事呢?那不是让我调试它吗(我觉得看到 in.read() 是问题是看到计数有用的),而不是解释它为什么会这样?现在发布代码。
-
如果你知道的话,我不会发送一个魔术字符串而是提前发送长度。并且您应该将 tcp 视为流而不是数据包(即输入可能具有与接收到的读取不同的块)。
标签: java sockets networking inputstream