Netty3 源碼分析 - ChannelHandlerContext

來源:互聯網
上載者:User

標籤:channelhandlercontex   channelpipeline   

Netty3 源碼分析 - ChannelHandlerContext
ChannelHandlerContext存在的意義是可以讓其管理的Handler與Pipeline或其他handlers進行互動,ChannelHandler的理解在前面說過。
發送事件:可以調用 sendUpstream(ChannelEvent) 或sendDownstream(ChannelEvent)將一個事件傳遞給這個Pipeline中與其最近的那個Handler。
修改pipeline:調用 getPipeline()可以得到這個Handler所屬的ChannelPipeline對象,當然也可以運行時更新(加入,移除)這個pipeline中的Handlers。提取備用(Retrieving for later use):可以持有一個ChannelHandlerContext,為了以後使用。( 這裡有待深入理解
儲存狀態資訊:見ChannelHandler。 一個Handler可以有多個Context:這就意味著如果這些Context加入到了不同的pipeline中,這些Handler執行個體就會執行多次。下面這個API中的例子,對於每次接收到的一個數字,做累積,把結果存在attachment中。 public  class FactorialHandler  extends SimpleChannelHandler {
      // This handler will receive a sequence of increasing integers starting      // from 1.      @Override       public  void messageReceived(ChannelHandlerContext ctx, MessageEvent evt) {          Integer a = (Integer) ctx.getAttachment();          Integer b = (Integer) evt.getMessage();
            if (a ==  null ) {              a = 1;          }          ctx.setAttachment(Integer.  valueOf(a * b));     }}FactorialHandler fh =  new FactorialHandler();ChannelPipeline p1 = Channels.  pipeline();p1.addLast( "f1" , fh);p1.addLast( "f2" , fh);
ChannelPipeline p2 = Channels.  pipeline();p2.addLast( "f3", fh);p2.addLast( "f4", fh);如果倆pipeline都啟動的話,就會正確的執行四次乘法操作。
到這裡,再看ChannelHandlerContext 的源碼就一目瞭然了。 public  interface ChannelHandlerContext {
      // 得到這個pipeline所屬的Channel,等價於getPipeline().getChannel()     Channel getChannel();
      // Handler所屬的pipeline     ChannelPipeline getPipeline();
      // Handler都有對應的名字     String getName();
      // 返回這個Context維護的Handler     ChannelHandler getHandler();
      // 對應的Handler類型,看是否是ChannelUpstreamHandler,ChannelDownstreamHandler執行個體       boolean canHandleUpstream();       boolean canHandleDownstream();
      //傳遞事件給最近的Handler       void sendUpstream(ChannelEvent e);       void sendDownstream(ChannelEvent e);

     Object getAttachment();       void setAttachment(Object attachment);}








Netty3 源碼分析 - ChannelHandlerContext

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.