Domanda

I'm experimenting with a custom outbound message handler in Netty 4 and cannot seem to get it to work. The handler just logs a statement and is added toward the bottom of the channel pipeline. My understanding is that these handlers are invoked from the bottom up, in order, once a write operation is issued. The idea with the custom handler was that it would be executed prior to any other outbound message handlers.

Unfortunately, when I add this logging handler to the pipeline, I see the log statement but then Netty seems to immediately close the connection. Here's my channel initializer and outbound handler code.

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);
}

Finally, here's the logger output.

[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
È stato utile?

Soluzione

Answering my own question in case anyone else finds this.

It turns out I needed to add the message to the next outbound message buffer (which I believe has the effect of passing it to the next handler in the chain). I also needed to retain the message. The updated code now looks like...

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());
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top