Frage

This is a code snippet where the problem is happening:

public static byte[] copyLargeExt(InputStream input) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*8];
        int n = 0;
        while(-1 != (n = input.read(buffer))) {
            baos.write(buffer, 0, n);
        // i just append this pattern ({###END###}) to force the break  
           /*if(baos.toString(UTF8.name()).endsWith("{###END###}")) {
                break;
            }*/
        }
        return baos.toByteArray();
    }

Can someone help me?

War es hilfreich?

Lösung

The code in the question reads to the end of the socket stream. If the method is blocking and in the read call, then that can only mean that the other end has not closed its corresponding output stream yet.

You have two choices:

  • Change the other end to close its outputstream so that this code will see an EOF.

  • Change the "protocol" so that this code knows how many bytes of data to expect ... and reads exactly that number of bytes.

Andere Tipps

In Java.
If the Server only Socket.close() without OutputStream.close() first, the Client's InputStream.read() will not return -1.
Instead, the Client's InputStream.read() will block until timeout. So the best practice on Server is:

OutputStream.close();
InputStream.close();
Socket.close();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top