使用 netty 解析 XML 字符串



我正在通过TCP以标准xml格式接收消息,我正在通过我的netty客户端收听。应该如何编写我的管道,以便我可以解析以<abc>....</abc>开头和结尾的字符串?

我猜应该有一个字符串解码器和另一个自定义处理程序(netty 定义或其他方式(来处理从 TCP 流解析 XML。

像下面这样?

public Bootstrap createBootstrap(final Bootstrap b, EventLoopGroup eventLoop) {
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    ReconnectionClient reconnectionClient = new ReconnectionClient(this);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(reconnectionClient);
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));             
            pipeline.addLast(new ClientHandler()); // deals with String parsing                
        }
    });
    // Use command line arguments to pass the socket
    b.connect(serverIP, serverPort).addListener(new ConnectionListener(this));
    return b;
}

我的问题的第二部分是如何解析通过TCP传输的单个XML字符串?例如,应该在实现此功能的 ClientHandler(( 中编写哪些代码?

如果你只想用netty解码XML,你可以使用inbuild XML-decoder(这个处理程序不需要StringDecoder(。如果要在<abc>标记后开始处理XML文档,只需等待名称为abc的XmlElementStart对象即可。关闭标记也是如此,但具有 XmlElementEnd 对象。

最新更新