我正在尝试使用 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.
我正在刷新来自网络服务器的每次发送,但输入流似乎没有实现可刷新。
谁能解释一下为什么会发生这种情况?
编辑: 这就是我读取内容的方式。基本上这是一个循环,然后写入文件。
in.read(byteBuffer, 0, BUFSIZE);
最佳答案
如果您的期望是读取将填充缓冲区,或者准确接收对等方通过单个 write()
发送的内容,则此处的错误是您的期望,而不是 read()。
未指定一次传输多于一个字节,并且不能保证保留写入边界。
如果不将 read()
的结果存储到变量中,就不可能编写正确的代码。
关于java - InputStream in.read() 的行为与预期不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30112877/