I'm writing a simple client/server network application that sends and receives fixed size messages through a TCP socket.
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).
Later on, I read the Javadoc for that method:
public int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. 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.
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?
The read (byte [] b, int off, int len) method of Java DataInputStream class determines the number of bytes to read. The len bytes of data from the contained input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero. b: b is buffer into which the data is read.
Java InputStream blocking read. According to the java api, the InputStream.read() is described as: If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
InputStream reads bytes with the following read methods : read (byte [] b) — reads up to b.length bytes of data from this input stream into an array of bytes. read (byte [] b, int off, int len) — reads up to len bytes of data from this input stream into an array of bytes. read () — reads one byte from the file input stream.
The read (byte [] b) method of Java DataInputStream class is used to read some number of bytes from the input stream and stores them into the buffer array b. The read () method blocks until input data are available, end of file is detected, or an exception is thrown. b: It is the buffer array into which the data is read from this stream.
Use DataInputStream.readFully
. Its Javadocs directs the reader to the DataInput
Javadocs Javadocs, which state:
Reads some bytes from an input stream and stores them into the buffer array
b
. The number of bytes read is equal to the length ofb
.
InputStream in = ...
DataInputStream dis = new DataInputStream( in );
byte[] array = ...
dis.readFully( array );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With