netty 學習 FrameDecoder

來源:互聯網
上載者:User

標籤:

我們接下來就看和業務息息相關的解碼器,首先我們來看FrameDecoder,這個東西應該是所有的解碼器都會實現這個,所以我們來重點看一下。

        FrameDecoder產生的根源就是TCP/IP資料包的傳輸方式決定的,包在傳輸的過程中會分區和重組,

正如javadoc裡面所說的:

    用戶端在發送的時候的序列如下:

+-----+-----+-----+

| ABC | DEF | GHI |

+-----+-----+-----+

伺服器端在接受到後可能會變成下面的序列:

+----+-------+---+---+

| AB | CDEFG | H | I |

+----+-------+---+---+

FrameDecoder協助我們將接受到的資料包整理成有意義的資料幀,例如,可以協助我們將資料包整理成

下面的資料格式:

+-----+-----+-----+

| ABC | DEF | GHI |

+-----+-----+-----+

我們接下來就看看FrameDecoder的實現吧:

FrameDecoder是繼承SimpleChannelUpstreamHandler的,我們首先來看一下messageReceived的實現:

        

Java代碼  
  1. @Override  
  2.    public void messageReceived(  
  3.            ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
  4.   
  5.        Object m = e.getMessage();  
  6.        if (!(m instanceof ChannelBuffer)) {  
  7.            ctx.sendUpstream(e);  
  8.            return;  
  9.        }  
  10.   
  11.        ChannelBuffer input = (ChannelBuffer) m;  
  12.        if (!input.readable()) {  
  13.            return;  
  14.        }  
  15.   
  16.        ChannelBuffer cumulation = cumulation(ctx);  
  17.        if (cumulation.readable()) {  
  18.            cumulation.discardReadBytes();  
  19.            cumulation.writeBytes(input);  
  20.            callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress());  
  21.        } else {  
  22.            callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());  
  23.            if (input.readable()) {  
  24.                cumulation.writeBytes(input);  
  25.            }  
  26.        }  
  27.    }  

        這個裡面首先會檢查input的可讀性,這個比較好理解,關鍵是cumulation,

我們首先來看一下cumulation的實現吧:

Java代碼  
  1. private ChannelBuffer cumulation(ChannelHandlerContext ctx) {  
  2.         ChannelBuffer c = cumulation;  
  3.         if (c == null) {  
  4.             c = ChannelBuffers.dynamicBuffer(  
  5.                     ctx.getChannel().getConfig().getBufferFactory());  
  6.             cumulation = c;  
  7.         }  
  8.         return c;  
  9.     }  

        這個函數很簡單,就是如果cumulation為空白的時候初始化一下,如果不為空白,就返回。我們得思考一下什麼時候cumulation為空白,什麼時候不為空白。我們再回過頭來看一下上面的實現吧。如果cumulation可讀,cumulation.discardReadBytes函數的作用是將0到readIndex之間的空間釋放掉,將readIndex和writeIndex都重新標記一下。然後將讀到的資料寫到buffer裡面。如果cumulation不可讀,在調callDecode,如果發現從不可讀狀態到可讀狀態,則將讀到的資料寫到緩衝區裡面。

        我們再來看callDecode的實現:

Java代碼  
  1. private void callDecode(  
  2.             ChannelHandlerContext context, Channel channel,  
  3.             ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception {  
  4.   
  5.         while (cumulation.readable()) {  
  6.             int oldReaderIndex = cumulation.readerIndex();  
  7.             Object frame = decode(context, channel, cumulation);  
  8.             if (frame == null) {  
  9.                 if (oldReaderIndex == cumulation.readerIndex()) {  
  10.                     // Seems like more data is required.  
  11.                     // Let us wait for the next notification.  
  12.                     break;  
  13.                 } else {  
  14.                     // Previous data has been discarded.  
  15.                     // Probably it is reading on.  
  16.                     continue;  
  17.                 }  
  18.             } else if (oldReaderIndex == cumulation.readerIndex()) {  
  19.                 throw new IllegalStateException(  
  20.                         "decode() method must read at least one byte " +  
  21.                         "if it returned a frame (caused by: " + getClass() + ")");  
  22.             }  
  23.   
  24.             unfoldAndFireMessageReceived(context, remoteAddress, frame);  
  25.         }  
  26.   
  27.         if (!cumulation.readable()) {  
  28.           this.cumulation = null;  
  29.         }  
  30.     }  
  31.       

 

 

       這個裡面上面是一個迴圈,首先將讀指標備份一下,decode方法是交個子類實現的一個抽象方這個用來實現具體資料分幀的演算法,從這個裡面看到如果子類沒有讀到一幀資料,則返回null所以下面有一個判斷,是一點資料沒有讀呢,還是讀了一點,如果一點都沒有讀,就不需要再檢測了等下一次messageRecieved進行通知,如果發現讀了一點資料,就調用下一次分幀。如果讀了一幀資料就發送一個通知,unfold是針對讀到的迴圈資料要不要開啟的意思。到最後如果發現不是可讀狀態,

cumulation將會被設定成null。

 

最後來看一下cleanup的實現

Java代碼  
  1. private void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e)  
  2.             throws Exception {  
  3.         try {  
  4.             ChannelBuffer cumulation = this.cumulation;  
  5.             if (cumulation == null) {  
  6.                 return;  
  7.             } else {  
  8.                 this.cumulation = null;  
  9.             }  
  10.   
  11.             if (cumulation.readable()) {  
  12.                 // Make sure all frames are read before notifying a closed channel.  
  13.                 callDecode(ctx, ctx.getChannel(), cumulation, null);  
  14.             }  
  15.   
  16.             // Call decodeLast() finally.  Please note that decodeLast() is  
  17.             // called even if there‘s nothing more to read from the buffer to  
  18.             // notify a user that the connection was closed explicitly.  
  19.             Object partialFrame = decodeLast(ctx, ctx.getChannel(), cumulation);  
  20.             if (partialFrame != null) {  
  21.                 unfoldAndFireMessageReceived(ctx, null, partialFrame);  
  22.             }  
  23.         } finally {  
  24.             ctx.sendUpstream(e);  
  25.         }  
  26.     }  

    在這個裡面一般來說是在socket斷開的時候調用,這個時候如果發現buffer還是可讀狀態,還會努力的確保所有的資料已經被分幀,然後調用decodeLast

 

===========================================================================================

轉自http://blog.csdn.net/xiaolang85/article/details/12621663

netty 學習 FrameDecoder

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.