LengthFieldBasedFrameDecoder不调用下一个处理程序

时间:2019-03-27 10:24:26

标签: netty

我正在使用LengthFieldBasedFrameDecoder作为处理从客户端发送的入站流量的第一个处理程序。

长度:4个字节 有效负载:您好-5个字节

[0, 0, 0, 9, 72, 101, 108, 108, 111]

ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("frameDecoder", new PacketFrameDecoder());
            ch.pipeline().addLast(new GameServerHandler());
        }
    })
    .option(ChannelOption.SO_BACKLOG, 128)
    .childOption(ChannelOption.SO_KEEPALIVE, true);

// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync();

ByteToMessageDecoder中,我看到fireChannelRead(ctx, out, size)的调用被清空,大小为0。似乎没有异常。我已经在解码器中尝试了两种字节序。

public class PacketFrameDecoder extends LengthFieldBasedFrameDecoder {

    //Constants
    private static final int MAX_FRAME_LENGTH = Integer.MAX_VALUE;
    private static final int LENGTH_FIELD_OFFSET = 0;
    private static final int LENGTH_FIELD_LENGTH = 4;
    private static final int LENGTH_FIELD_ADJUSTMENT = 0;
    private static final int INITIAL_BYTES_TO_STRIP = 4;

    //Constructors
    public PacketFrameDecoder() {
        super(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH,
            LENGTH_FIELD_ADJUSTMENT, INITIAL_BYTES_TO_STRIP);

    }

}

此后,我想在扩展GameServerHandler的{​​{1}}中处理我的身体/有效载荷。

ChannelInboundHandlerAdapter

但是我的public class GameServerHandler extends ChannelInboundHandlerAdapter { /** * This method is called with the received message, whenever new data is received from a client. * @param context * @param message */ @Override public void channelRead(ChannelHandlerContext context, Object message) { Log.i("GameServerHandler"); //Breakpoint here ByteBuf in = (ByteBuf) message; try { String test = in.toString(io.netty.util.CharsetUtil.US_ASCII); Log.i(test); } finally { ReferenceCountUtil.release(message); } } @Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); context.close(); } } 中的channelRead没有被调用或触发。我不知道我在做什么错。

1 个答案:

答案 0 :(得分:1)

我刚刚发现问题似乎与长度调整有关。 我的标头(4个字节)包含在总长度中,因此有2个选项:

  1. 从“长度字段调整”中减去标题长度:LENGTH_FIELD_ADJUSTMENT = -4
  2. 发送消息时不封装报头长度,仅包含有效载荷