How to reliably tell when finished reading from a socket in Java? -
We are integrating with an external product, for which we need to communicate with it using java sockets. We have been able to read the small responses from the server with no problems, but the big reactions are creating some headaches.
I have made some changes in logic to deal with socket and now we have 90% of the big responses It still fails sometimes fails, in this case, this means that the Java client prevents reading from the socket before reading the full response. The client thinks that the reading is over, and normally closes - there is no exception or time incorporation is not included.
The current argument looks like this:
StringWriter response = new StringWriter (); PrintWriter author = new PrintWriter (response); Four [] buf = new four [4096]; Int readChars; Do {readChars = responseBufferedReader.read (buf); Writer (Written, 0, Reed Chairs); } While (readChars! = -1 & amp; ResponseBufferedReader.ready ()); responseBufferedReader
a BufferedReader
is wrapped around a wrapped around the code
wrapped around the InputStreamReader < / Code>> 'S InputStream
. This code works most of the time, but it seems that readChars! = -1
and ready ()
is not reliable enough to indicate that we have read all the content from the server, compared to the number of letters read in buffer size is also not reliable , Because the server seems to slow down in response to the response, so these numbers can be separated.
I have tried to resize the character buffer; It helped, but it is still not working 100%.
Is there a better and more reliable method of reading completely with socket
without knowing the size of the expected response? I'm doing some research on SocketChannel
s, but I'm not sure there is no need to make any profit by switching.
If this helps, then we are blocking a single, socket
connection to the server is configured for 100 seconds timeout socket
You should not have to check if a buffer reader is ready () tell it if you have done it possible That the bytes are still being read from the wire and the buffered reader has nothing for you, but the socket is not closed yet Has happened.
I'm not sure how much value buffrated readers are getting (well, this can help you with your performance). I expect the following to work better:
stringwitter feedback = new stringwriters (); PrintWriter author = new PrintWriter (response); Four [] buf = new four [4096]; Int readChars; Do {readChars = inputStreamReader.read (buf); Writer (Written, 0, Reed Chairs); } While (readChars! = -1);
I think that you are probably going out of the loop when there is a network barrier - the loop process is fast enough so that the reader is not ready yet and you assume you are reading (Even if you are not).
Comments
Post a Comment