My Java project (I'm the client side) consists of sending requests and reading responses through TCP socket connection. Over the socket I create an Output and Input Stream for sending and receiving data, respectively. All works well, except the end of the message, i.e., I send correctly my request through my DataOutputStream, the final response (through DataInputStream) is ok, but the reading always hangs 60 seconds on DataInputStream.read method. After that hang of 60 seconds all works great. There's my method:
private static int BUFFER_SIZE = 1024;
public void read(DataInputStream inputStream) throws IOException {
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[BUFFER_SIZE];
while ((len = inputStream.read(buf, 0, BUFFER_SIZE)) != -1) {
bos.write(buf, 0, len);
}
buf = bos.toByteArray();
// parse buf
}
I thinks it has something to do with the while loope control
((len = inputStream.read(buf, 0, BUFFER_SIZE)) != -1)
but I cannot figure out what! Since the response has no fixed size I don't know when to stop reading. I already try some configurations changing de BUFFER_SIZE, controling the loop over inputStream.available(), but sometimes the available value is 0 and the inputStream.read keep reading data. I really think that's a little detail I'm missing, but struggling to find it out! thanks
I figured ou a solution and concluded that my approach to the problem was wrong. I was reading the entire response and THEN parsing the result. Wrong. The solution is to parse the response as I read it. That way I know what I'm reading and I know when to stop reading (I have a little protocol documentation).
An IMPORTANT NOTE is to use
InputStream.readFully(byte[] b, int off, int len)
instead of
InputStream.read(byte[] b, int off, int len)
The method readFully will read exactly len bytes into buffer b. That way we guarantee the full reading of the response or chunk and not only a part of it. I had some problems with this too, sometimes it was working ok, other times not ok. Now with readFully works great. Thanks Titus, your hint were very assertive.