Search code examples
javanetwork-programmingniosocketchannel

Reading stream over TCP on a SocketChannel with undefined number of Bytes


I am trying to read a stream on a SocketChannel without defining the number of bytes.

The alternate solution i thought about is storing different ByteBuffers of a pre-defined size into a list which will allow me afterwards to allocate a new ByteBuffer of the received size and put the result inside.

The problem is that i am on blocking-mode and cannot find a valid condition to leave the loop i made on the read method check the code:

public static final Charset charsetUTF8 = Charset.forName("UTF-8");
public static final int BUFFER_SIZE = 1024;

public static String getUnbounded(String st, SocketAddress address) throws IOException {
    SocketChannel sc = SocketChannel.open(address);
    sc.write(charsetUTF8.encode(st));
    List<ByteBuffer> listBuffers = new ArrayList<>();
    ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);
    while( sc.read(buff) > -1){
        if(buff.remaining() == 0){
            listBuffers.add(buff);  
            buff.clear();
        }
    }

    listBuffers.add(buff);
    ByteBuffer finalBuffer = ByteBuffer.allocate(BUFFER_SIZE * listBuffers.size());
    for(ByteBuffer tempBuff: listBuffers){
    finalBuffer.put(tempBuff);
        tempBuff.clear();
    }
    finalBuffer.flip();

    return charsetUTF8.decode(finalBuffer).toString();
}

Any idea on how to solve this?


Solution

  • The solution is that to get out of the loop i had to call:

    sc.shutdownOutput();
    

    Which closes the writing stream without closing the reading stream and set the sc.read(buff) to -1