简体   繁体   中英

program hangs inside while loop for reading input stream from socket: Java

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?

As the BufferedInputStream method you are using does not block you get the situation that as soon as your InputStream does not have any data and is not closed you don't get a -1 but a 0. This will send your method into an endless loop.

So for reading local streams it is better to check for read() <= 0 as you usually get the data fast enough.
The best way is to make sure there is an eof by closing the stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM