【问题标题】:Handling message in Netty在 Netty 中处理消息
【发布时间】:2017-06-13 22:11:05
【问题描述】:

我是 Netty 的新手,需要以自定义方式处理消息。我有以下接口:

public interface Command{ }

public interface CommandFactory{
    Command(byte b)
}

public interface CommandProcessor{
    void process(Command c, Object arg)
}

现在我从客户端收到一些数据并想要处理它。我正在为此实施ReplayingDecoder<Void>

public class CommandDecoder extends ReplayingDecoder<Void>{
    private CommandFactory cmf;
    private CommandProcessor cmp;

   void decode(ChannelHandlerContext ctx, ByteBuf in, List<AnyRef> out){
       Command command = cmf.command (
         in.readByte()
       );

       String arg = new String (
         in.readBytes (
           in.readShort()
         ).array()
       );

      cmp.process(command, arg); //<------------ Here
  }
}

问题是我不确定。我在解码器中处理命令。至少可以说看起来很奇怪。也许我应该将解码后的commmandarg 进一步传递给channel pipeline

但是选择哪个ChannelInboundHandler 进行命令处理?

【问题讨论】:

    标签: java netty


    【解决方案1】:

    你是对的。最好将解码器和实际的业务逻辑分开进行命令处理。在这种情况下,最好的处理程序是SimpleChannelInboundHandler。一般来说,它只接受特定类型的消息。

    它可能看起来像这样:

    public class MyCommandHandler extends SimpleChannelInboundHandler<Command> {
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Command command) throws Exception {
             //process here your message
             //command.type;
             //command.args  
        }
    
    }
    

    所以在你解码你的命令之后:

    Command command = cmf.command (
             in.readByte(),
             new String (in.readBytes (in.readShort()).array())
           );
    

    您可以将其传递给管道中的下一个MyCommandHandler

    out.add(command);
    

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多