Netty 4出站消息处理程序关闭连接

时间:2013-05-10 05:40:40

标签: java handler netty outbound

我正在Netty 4中尝试自定义出站邮件处理程序,似乎无法使其正常工作。处理程序只记录一条语句,并添加到通道管道的底部。我的理解是,一旦发出写操作,就会从下到上调用这些处理程序。使用自定义处理程序的想法是它将在任何其他出站消息处理程序之前执行。

不幸的是,当我将此日志记录处理程序添加到管道时,我看到了日志语句,但随后Netty似乎立即关闭了连接。这是我的频道初始化和出站处理程序代码。

HttpOutboundHandler.java

public class HttpOutboundHandler extends ChannelOutboundMessageHandlerAdapter<DefaultFullHttpResponse> {
    private static final Logger logger = LoggerFactory.getLogger(HttpOutboundHandler.class);

    @Override
    public void flush(ChannelHandlerContext context, DefaultFullHttpResponse response)
            throws Exception {
        logger.debug("Executing outbound handler.");
    }
}

HttpChannelInitializer.java

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(1048576);
    pipeline.addLast("compressor", new HttpContentCompressor(gzipLevel));
    pipeline.addLast("outboundHandler", outboundHandler);
    pipeline.addLast(eventExecutorGroup, "inboundHandler", inboundHandler);
}

最后,这是记录器输出。

[DEBUG] (Slf4JLogger:71) - [id: 0xbddf00cf, /0:0:0:0:0:0:0:1:57402 => /0:0:0:0:0:0:0:1:8080] ACTIVE
[DEBUG] (HttpOutboundHandler:19) - Executing outbound handler.
[DEBUG] (Slf4JLogger:71) - [id: 0x942993c1, /0:0:0:0:0:0:0:1:57403 :> /0:0:0:0:0:0:0:1:8080] INACTIVE

1 个答案:

答案 0 :(得分:3)

回答我自己的问题,以防其他人发现此问题。

事实证明我需要将消息添加到下一个出站消息缓冲区(我认为这会将其传递给链中的下一个处理程序)。我还需要保留这条消息。更新的代码现在看起来像......

public class HttpOutboundHandler extends ChannelOutboundMessageHandlerAdapter<DefaultFullHttpResponse> {
    private static final Logger logger = LoggerFactory.getLogger(HttpOutboundHandler.class);

    @Override
    public void flush(ChannelHandlerContext context, DefaultFullHttpResponse response)
            throws Exception {
        logger.debug("Executing outbound handler.");
        ChannelHandlerUtil.addToNextOutboundBuffer(context, response.retain());
    }
}