出站消息的netty管道订单

时间:2017-05-02 19:43:58

标签: java netty

我正在使用Netty v4.1.9final并尝试从客户端向服务器发送消息。我尝试在客户端使用处理程序设置通道客户端初始化程序,如下所示:

final Bootstrap bootstrap = BootstrapGenerator.generate();
bootstrap.handler(new XmlClientInitializer());  

XMLClientInitializer

public class XmlClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        final ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("fileEncoder", new FileEncoder());
        pipeline.addLast("handler", new XmlSenderHandler());
    }
}

FileEncoder

public class FileEncoder extends MessageToByteEncoder<String> {

XmlSenderHandler

public class XmlSenderHandler extends ChannelOutboundHandlerAdapter {

    private static final Logger log = LogManager.getLogger(XmlSenderHandler.class.getName());
    private static ChannelHandlerContext ctx;

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        log.info("attempting to write messages to server {}", msg.toString());
        ctx.write(msg, promise);
    }

    @Override
    @SuppressWarnings("FutureReturnValueIgnored")
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

即使FileEncoder首先在管道中定义,它也会在xml处理程序之后被调用(这不是我所寻求的)。这是因为FileEncoder正在扩展MessageToByteEncoder,还是我错误地配置了频道?

1 个答案:

答案 0 :(得分:1)

不,管道配置正确。关键是入站事件从第一个处理程序处理到最后一个处理程序,出站事件从最后一个处理程序处理到第一个处理程序。 ChannelPipeline doc