I have the following code to read an input stream from a socket connection:
private ByteBuffer toByteBuffer(BufferedInputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int l;
byte[] data = new byte[256];
while ((l = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, l);
}
buffer.flush();
return ByteBuffer.wrap(buffer.toByteArray());
}
In the first iteration of the while loop, everything goes fine and I am able to get the data into the buffer. But then it gets stuck at while ((l = is.read(data, 0, data.length)) != -1) {
I think (and I might be wrong) it is because it is waiting for more data from the socket, which is never going to come.
How do I handle this situation/hang?