Netty 读取了准确的字节数

Netty read exact number of bytes

我正在扩展 ChannelInboundHandlerAdapter 并想读取确切的字节数。

public class Reader extends ChannelInboundHandlerAdapter{

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ByteBuf b = (ByteBuf) msg;
        byte size = b.readByte();
        //Now I want to read exactly size bytes from the channel
        //and then again read the number of bytes and read the bytes...
    }

}

问题是我们从 ByteBuf. How to read more from the Channel?

中读取的字节数可能少于所需的字节数

仅供阅读,您可以使用 b.readSlice(size)。 但是,正如您所提到的,缓冲区可能还没有足够的数据来容纳您的消息。因此,您需要在创建消息之前完全使用数据。对于这种情况,我建议您使用内置的 ByteToMessageDecoder 处理程序。它将为您处理低级字节。因此,使用 ByteToMessageDecoder 您的代码将如下所示:

class Reader extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte size = in.readByte();
        if (in.readableBytes() < size) {
           in.resetReaderIndex();
           return;
        }

        ByteBuf bb = in.readSlice(size);
        //make whatever you want with bb
        Message message = ...; 
        out.add(message);
    }
}

所以在本例中,您读取了消息需要读取的字节数 - size。然后检查 in 缓冲区是否有足够的数据可供使用。如果不是 - 你 return 控制 ByteToMessageDecoder 直到它阅读更多。并重复,直到您有足够的数据来构建您的消息。