[英]Java InputStream.read(byte[], int, int) method, how to block until the exact number of bytes has been read
I'm writing a simple client/server network application that sends and receives fixed size messages through a TCP socket. 我正在编写一个简单的客户端/服务器网络应用程序,通过TCP套接字发送和接收固定大小的消息。
So far, I've been using the getInputStream()
and getOutputStream()
methods of the Socket
class to get the streams and then call the read(byte[] b, int off, int len)
method of the InputStream
class to read 60 bytes each time (which is the size of a message). 到目前为止,我一直在使用
Socket
类的getInputStream()
和getOutputStream()
方法来获取流,然后调用InputStream
类的read(byte[] b, int off, int len)
方法来读取60每次字节数(这是消息的大小)。
Later on, I read the Javadoc for that method: 后来,我阅读了该方法的Javadoc:
public int read(byte[] b, int off, int len) throws IOException
public int read(byte [] b,int off,int len)抛出IOException
Reads up to len bytes of data from the input stream into an array of bytes.
将输入流中最多 len个字节的数据读入一个字节数组。 An attempt is made to read as many as len bytes, but a smaller number may be read .
尝试读取len个字节, 但可以读取较小的数字 。 The number of bytes actually read is returned as an integer.
实际读取的字节数以整数形式返回。
I was wondering if there's any Java "out-of-the-box" solution to block until len bytes have been read, waiting forever if necessary. 我想知道是否有任何Java“开箱即用”的解决方案要阻止,直到len字节被读取,必要时永远等待。
I can obviously create a simple loop but I feel like I'm reinventing the wheel. 我显然可以创建一个简单的循环,但我觉得我正在重新发明轮子。 Can you suggest me a clean and Java-aware solution?
你能建议我一个干净的Java感知解决方案吗?
The simple loop is the way to go. 简单的循环是要走的路。 Given the very small number of bytes you're exchanging, I guess it will need just one iteration to read everything, but if you want to make it correct, you have to loop.
鉴于您正在交换的字节数非常少,我想它只需要一次迭代来读取所有内容,但如果要使其正确,则必须循环。
I think the correct version of ratchet freak's answer is this : 我认为正确版本的棘轮怪物的答案是这样的:
for (int index = 0; index < toRead && (read = inputStream.read(bytes, index, toRead-index))>0 ; index+= read);
it stops reading if read returns -1 如果read返回-1,它将停止读取
a simple for one-liner will do the trick 一个简单的单行程将成功
int toread = 60;
byte[] buff;
for(int index=0;index<toread;index+=in.read(buff,index,toread-index));
but most of the time the only reason less bytes would be read is when the stream ends or the bytes haven't all been flushed on the other side 但大多数时候,读取较少字节的唯一原因是当流结束或者字节没有全部被刷新到另一端时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.