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));
    }
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM