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 IOExceptionReads 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?
Use
DataInputStream.readFully. Its Javadocs directs the reader to theDataInputJavadocs Javadocs, which state: