Socket reading using BufferedInputStream

Adam picture Adam · Jan 13, 2014 · Viewed 7.2k times · Source

I'm using Java's BufferedInputStream class to read bytes sent to a socket. The data to the socket is HTTP form so generally is a header with defined content-length, then some content.

The problem I'm having is that sometimes BufferedInputStream.read() will not read the full amount of data sent to it. It returns the number of bytes read but this is much less than has been sent. I have verified the bytes sent with Wireshark and can confirm the full message is being transmitted.)

Sample code below:

BufferedInputStream inFromClient = new BufferedInputStream(socket.getInputStream());
int contentLength = getContentLengthFromHeader();    
byte[] b = new byte[contentLength];
int bytesRead = inFromClient.read(b, 0, contentLength);

Once read() is finished sometimes bytesRead is equal to contentLength but on other occasions read() does not seem to read as far as the end of the content. Does anyone have any ideas on what is happening? Is Java buffering output? Are there better ways of reading from sockets?

Answer

user207421 picture user207421 · Jan 14, 2014

You're assuming that read() fills the buffer. Check the Javadoc. It transfers at least one byte, that's all it says.

You don't need both a large buffer and a BufferedInputStream. Change the latter to DataInputStream.readFully().