バイト数を定義せずに SocketChannel でストリームを読み取ろうとしています。
私が考えた別の解決策は、事前定義されたサイズの異なる ByteBuffers をリストに格納することです。これにより、後で受信したサイズの新しい ByteBuffer を割り当てて、結果を中に入れることができます。
問題は、私がブロッキングモードにあり、読み取りメソッドで作成したループを終了する有効な条件が見つからないことです。コードを確認してください:
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();
}
これを解決する方法について何か考えはありますか?