netty实现多个handler顺序调用

在netty中,一次数据交互,可以由多个handler去处理,例如 handler1 和 handler2,那么,在前面那个handler的 messageReceived 的最后要加上 ctx.sendUpstream(e);

理论请见:

http://netty.io/3.5/api/org/jboss/netty/channel/ChannelPipeline.html

 A ChannelEvent can be handled by either a ChannelUpstreamHandler or aChannelDownstreamHandler and be forwarded to the closest handler by calling ChannelHandlerContext.sendUpstream(ChannelEvent) or ChannelHandlerContext.sendDownstream(ChannelEvent).

 

代码:

public class Handler1 extends SimpleChannelUpstreamHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        System.out.println("1 messagereceived");
        String a = "11";
        Object o = a;
        ctx.getChannel().write(a);
        ctx.sendUpstream(e);     }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        e.getChannel().close();
    }

}
public class Handler2 extends SimpleChannelUpstreamHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        System.out.println("2 messagereceived");
        e.getChannel().close();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        e.getChannel().close();
    }
}
public class TcpServer {

    public static void main(String[] args) {
        System.out.println("starting a tcp server...");
        ServerBootstrap sb = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), 
                Executors.newCachedThreadPool())
        );
        sb.setPipelineFactory(new PKServerPipelineFactory());
        sb.setOption("child.tcpNoDelay", true);
        sb.setOption("child.keepAlive", true);
        sb.bind(new InetSocketAddress(9999));
    }
}

 

 

 

你可能感兴趣的:(handler)