java - 使用netty 4.1.9进行xml消息处理

标签 java xml netty

我正在服务器上使用 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 帧解码器,则会收到编译错误“xmlframedecoder 中没有可用的默认构造函数”。

最佳答案

我最终在 channel 初始值设定项中使用了 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);
    }
}

关于java - 使用netty 4.1.9进行xml消息处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172430/

相关文章:

java - Netty 4 WebSocket 应用程序、线程、同步

java - 不同线程中的 Hibernate AssertionFailure

c# - 使用 NPOI 时出现无法理解的错误

java - 使用多种类型的数据包实现 Protobuf3 的最佳方法是什么?

适用于小屏幕的 Android eclipse 图片

python - Unicode解码错误: 'charmap' codec can't decode byte 0x83 in position 7458: character maps to <undefined>

netty - 如何管理标识您的协议(protocol)的前缀字节序列

java - 如何将弹出菜单添加到 JTextField

Java正则表达式,匹配数学表达式中的变量

Java 的新 Scanner vs Scanner.create()?