我对使用netty不太熟悉,对ChannelPipeline的文档有疑问。这是确切的内容:

 static final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
 ...

 ChannelPipeline pipeline = ch.pipeline();

 pipeline.addLast("decoder", new MyProtocolDecoder());
 pipeline.addLast("encoder", new MyProtocolEncoder());

 // Tell the pipeline to run MyBusinessLogicHandler's event handler methods
 // in a different thread than an I/O thread so that the I/O thread is not blocked by
 // a time-consuming task.
 // If your business logic is fully asynchronous or finished very quickly, you don't
 // need to specify a group.
 pipeline.addLast(group, "handler", new MyBusinessLogicHandler());


我不太了解MyBusinessLogicHandler类。它应该实现DuplexChannelHandler还是其他的东西?例如,在我的特殊情况下,我有以下课程:

public class Packet{}


我想将某些字节序列解码为Packet,提供给MyBusinessLogicHandler从而生成一些Packet。然后再次将其编码为字节流,以发送回客户端。我目前这样看:

public class MyBusinessLogicHandler extends SimpleChannelInboundHandler<MyModel>{
    public void channelRead0(ChannelHandlerContext ctx, Packet msg){
         Packet rslt = null;
         //Do some complicated business logic
         ctx.write(rslt);
    }
}


我不确定这是否是在netty中做事的常用方法。你能澄清一下吗?

最佳答案

是的这是实现MyBusinessLogicHandler的完全正确的方法。您不需要DuplexChannelHandler,因为您在管道中已经有了MyProtocolEncoder(我想实现了ChannelOutboundHandler)。
因此,当您调用ctx.write(rslt)时,将触发出站处理程序的写事件。

DuplexChannelHandler仅在您要在同一类中实现编码器和解码器的情况下才有用。例如,您可以通过加入MyProtocolEncoderMyProtocolDecoder来实现。

07-26 06:35