2017-04-02 26 views
0

我在使用netty 4.1.9从服务器接收来自Netty客户端的XML消息。客户端能够将xml消息发送到服务器。但是,在服务器端,我需要能够将它们解码为单个xml消息(而不是一系列字节)。我看着xml帧解码器,但无法弄清楚最好的方法。希望指出正确的方向。使用netty 4.1.9进行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中没有可用的默认构造函数”。

回答

0

我最终在我的通道初始化器中使用了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()); 

处理

公共类ServerReceiverHandler扩展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); 
}