使用 netty 4.1.9 进行 xml 消息处理

using netty 4.1.9 for xml message processing

我在服务器上使用 netty 4.1.9 从 Netty 客户端接收 XML 消息。客户端能够向服务器发送 xml 消息。但是,在服务器端,我需要能够将它们解码为单个 xml 消息(而不是一系列字节)。我查看了 xml 帧解码器,但无法找到最佳方法。希望能指出正确的方向。

初始化程序:

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        log.info("init channel called");
        ChannelPipeline pipeline = ch.pipeline();
        //add decoder for combining bytes for xml message
        pipeline.addLast("decoder", new XmlMessageDecoder());

        // handler for business logic.
        pipeline.addLast("handler", new XmlServerHandler()); 
}

我无法使用 xml 帧解码器。如果我尝试在 mxl 消息解码器中扩展 xml 帧解码器,我会得到编译错误 "there is no default constructor available in xmlframedecoder"。

我最终在我的通道初始化器中使用了 XmlFrameDecoder,它的输出被传递到处理程序,在那里我能够从 ByteBuf 读取 XML 消息。

初始化器

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

    // idle state handler
    pipeline.addLast("idleStateHandler", new IdleStateHandler(60,
            30, 0));
    pipeline.addLast("myHandler", new IdleHandler());

    //add decoder for combining bytes for xml message
    pipeline.addLast("decoder", new XmlFrameDecoder(1048576));  

    // handler for business logic.
    pipeline.addLast("handler", new ServerReceiverHandler()); 
}

处理程序

public class ServerReceiverHandler extends ChannelInboundHandlerAdapter {

    ChannelHandlerContext ctx;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final ByteBuf buffer = (ByteBuf)msg;
        //prints out String representation of xml doc
        log.info("read : {}" + buffer.toString((CharsetUtil.UTF_8)));
        ReferenceCountUtil.release(msg);
    }
}