Netty的ByteToMessageDecoder模块阻塞问题

新手上路,请多包涵

尝试使用Netty接收TCP传输的消息,但是发现如果对象发送消息频率过高,就会出现Decorder中消息不再读取的情况。
服务端代码如下:

public class Server {

private static Logger log = Logger.getLogger(Server.class);
final static int REMOTE_PORT = 17650;

@PostConstruct  
public void bind() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap
                .group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536))
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //添加解码
                        socketChannel.pipeline().addLast(new Decoder());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(REMOTE_PORT).sync();
        channelFuture.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}
Decoder解码器摘自《Netty实战》一书的例子,如下:

public class Decoder extends ByteToMessageDecoder {

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
    int messageLength = in.readableBytes();
    if (messageLength>=4){
        out.add(in.readInt());
    }
    //打印日志
    System.out.println(in.isReadable());
    System.out.println("readerIndex:"+in.readerIndex());
    System.out.println("writerIndex:"+in.writerIndex());
    System.out.println("capacity:"+in.capacity());
    System.out.println("refcount:"+in.refCnt());
    System.out.println("isWritable:"+in.isWritable());
}

}
阻塞时,打印的日志如下:

true
readerIndex:23536
writerIndex:23538
capacity:65536
refcount:1
isWritable:true
打印出上面这条日志以后,就再也收不到客户端发送的消息了

阅读 3.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进