2017-06-13 73 views
2

我是Netty的新手,需要以自定義的方式處理郵件。我有以下接口: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可供選擇用於命令處理?

回答

2

你說得對。將解碼器和實際業務邏輯分開以進行命令處理會更好。在這種情況下,最好的處理程序將是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 
    } 

} 

所以你解碼你的命令後:

out.add(command); 

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

你可以把它在管道與傳遞到下一MyCommandHandler