gpt4 book ai didi

java - 在 SocketChannel 上通过 TCP 读取未定义字节数的流

转载 作者:行者123 更新时间:2023-12-01 13:17:16 24 4
gpt4 key购买 nike

我试图在不定义字节数的情况下读取 SocketChannel 上的流。

我想到的替代解决方案是将预定义大小的不同 ByteBuffer 存储到一个列表中,这将允许我随后分配接收大小的新 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();
}

知道如何解决这个问题吗?

最佳答案

你不能仅仅clear()字节缓冲区。您需要分配一个新的;否则,相同的缓冲区将被重复添加到 listBuffers 中。

ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);
while( sc.read(buff) > -1){
if(buff.remaining() == 0){
listBuffers.add(buff);
buff = ByteBuffer.allocate(BUFFER_SIZE);
}
}
if (buff.position() > 0) {
listBuffers.add(buff);
}

由于最后一个缓冲区可能未(可能不会)已满,因此您应该考虑到这一点来计算 finalBuffer 大小。

关于java - 在 SocketChannel 上通过 TCP 读取未定义字节数的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22366301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com