<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Chan Chen Coding...

    Netty 4.0 源碼分析(八):Netty 4.0中的io.netty.buffer包

    Netty 4.0的源碼結(jié)構(gòu)與之前的3.X版本發(fā)生了較大的變化,以下是Netty 4.0源碼的層次結(jié)構(gòu)


    netty/

       common/     - utility and logging

       buffer/     - buffer API

       transport/  - channel API and its core implementations

       handler/    - channel handlers

       codec/      - codec framework

       codec-http/ - HTTP, Web Sockets, SPDY, and RTSP codec

       example/    - examples

       all/        - generates an all-in-one JAR

       tarball/    - generates a tarball distribution

     

    在接下來的源碼分析中,筆者打算對(duì)每個(gè)包實(shí)現(xiàn)的功能做詳細(xì)的分析(除了example包,all包和tarball包)。在這篇文章中,筆者將對(duì)buffer包進(jìn)行分析。關(guān)于ByteBufreadIndex,writeIndexcapacity可以閱讀之前的另外一篇文章《Netty 4.0 源碼分析(四):ByteBuf》。

     

    Netty 4.0是一個(gè)異步NIO的消息通信框架,在分布式環(huán)境下,服務(wù)器之間的消息傳輸是基于I/O流的,在流傳輸中,字節(jié)是最小的傳輸單位,每個(gè)I/O流可以看做是對(duì)字節(jié)數(shù)組的操作。Buffer包中的ByteBuf實(shí)際上就是一個(gè)字節(jié)數(shù)組。

     

    大端(Big Endian)和小段(Little Endian

    在開始討論buffer包之前,有必要了解一下大端(Big Endian)和小段(Little Endian)的區(qū)別。大端(Big Edian)和小端(Little Endian)是內(nèi)存中數(shù)據(jù)儲(chǔ)存的字節(jié)序。不同體系的CPU在內(nèi)存中的數(shù)據(jù)存儲(chǔ)往往存在著差異。例如,Intelx86系列處理器將低序字節(jié)存儲(chǔ)在起始地址,而一些RISC架構(gòu)的處理器,如IBM370主機(jī)使用的PowerPCMotorola公司生產(chǎn)的CPU,都將高序字節(jié)存儲(chǔ)在起始位置。這兩種不同的存儲(chǔ)方式被稱為Little EndianBig Endian

    Java中,Big Endian, Little Endian跟多字節(jié)類型的數(shù)據(jù)有關(guān),比如int,short,long型,而對(duì)單字節(jié)數(shù)據(jù)byte卻沒有影響。BIG-ENDIAN就是低位字節(jié)排放在內(nèi)存的高端,高位字節(jié)排放在內(nèi)存的低端。而LITTLE-ENDIAN正好相反。

    Big Endian 和 Little Endian

      比如 int a = 0x05060708

      在BIG-ENDIAN的情況下存放為:

      字節(jié)號(hào) 0 1 2 3

      數(shù)據(jù)   05 06 07 08

      在LITTLE-ENDIAN的情況下存放為:

      字節(jié)號(hào) 0 1 2 3

      數(shù)據(jù)   08 07 06 05


     

    如果網(wǎng)絡(luò)上全部是PowerPC,SPARCMotorola CPU的主機(jī)那么不會(huì)出現(xiàn)任何問題,但由于實(shí)際存在大量的IA架構(gòu)的CPU,所以經(jīng)常出現(xiàn)數(shù)據(jù)傳輸錯(cuò)誤。

    所有網(wǎng)絡(luò)協(xié)議都是采用Big Endian的方式來傳輸數(shù)據(jù)的。所以有時(shí)我們也會(huì)把Big Endian方式稱之為網(wǎng)絡(luò)字節(jié)序。當(dāng)兩臺(tái)采用不同字節(jié)序的主機(jī)通信時(shí),在發(fā)送數(shù)據(jù)之前都必須經(jīng)過字節(jié)序的轉(zhuǎn)換成為網(wǎng)絡(luò)字節(jié)序后再進(jìn)行傳輸。

     

    Netty 4.0的,默認(rèn)的字節(jié)序是Big Endian(網(wǎng)絡(luò)字節(jié)序),在io.netty.buffer.Unpooled類中,定義了兩個(gè)ByteOrder類型的靜態(tài)變量

        /**
         * Big endian byte order.
         
    */
        public static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN;
        /**
         * Little endian byte order.
         
    */
        public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;

     

     如果要改變改變字節(jié)序,可以調(diào)用io.netty.buffer.ByteBuf接口的order(ByteOrder endianness)方法。調(diào)用order方法,可以返回當(dāng)前ByteBuf對(duì)象的字節(jié)序。

        /**
         * Returns the endianness of this buffer.
         
    */
        ByteOrder order();
        /**
         * Returns a buffer with the specified endianness which shares the whole region,
         * indexes, and marks of this buffer.  Modifying the content, the indexes, or the marks of the
         * returned buffer or this buffer affects each other's content, indexes, and marks.  If the
         * specified endianness is identical to this buffer's byte order, this method can
         * return {
    @code this}.  This method does not modify readerIndex or writerIndex of this buffer.
         
    */
        ByteBuf order(ByteOrder endianness);

     

    ChannelByteBuf的理解

    Netty中,Channel是負(fù)責(zé)數(shù)據(jù)讀寫的對(duì)象,類似于java舊的I/Ostream。Channel是雙向的,既可以write,也可以read。在NIO中,用戶不能直接從Channel中讀寫數(shù)據(jù),而是應(yīng)該通過ByteBuf來進(jìn)行讀寫操作,然后通過ByteBuf讀寫數(shù)據(jù)到Channel中??梢韵胂笠粋€(gè)伐木場,Channel就是某個(gè)含有大量需要砍伐的樹木(數(shù)據(jù))的采伐區(qū),要想取得這些樹木(數(shù)據(jù)),就需要一輛卡車來運(yùn)輸這些樹木(數(shù)據(jù)),這里的卡車就是ByteBuf(緩沖器),當(dāng)卡車(ByteBuf)滿載而歸的時(shí)候,我們再從卡車中獲得樹木(數(shù)據(jù))。

     

    Netty 4.0中的buffer

    Netty 4.0中的io.netty.buffer包,總共定義了七個(gè)接口,十五個(gè)類,一個(gè)Enums類型。下圖是他們之間的關(guān)系


    Io.netty.buffer包中的關(guān)系

    Unpooled是個(gè)幫助類,是一個(gè)final class,并且它的構(gòu)造器也是私有的,這意味的無法被別的類繼承,也無法通過new運(yùn)算符來創(chuàng)建一個(gè)Unpooled對(duì)象。Unpool類的目的就是用于創(chuàng)建ByteBuf對(duì)象。

        /**
         * Creates a new big-endian Java heap buffer with the specified
         * {
    @code capacity}.  The new buffer's {@code readerIndex} and
         * {
    @code writerIndex} are {@code 0}.
         
    */
        public static ByteBuf buffer(int initialCapacity, int maxCapacity) {
            if (initialCapacity == 0 && maxCapacity == 0) {
                return EMPTY_BUFFER;
            }
            return new HeapByteBuf(initialCapacity, maxCapacity);
        }
        /**
         * Creates a new big-endian direct buffer with the specified
         * {
    @code capacity}.  The new buffer's {@code readerIndex} and
         * {
    @code writerIndex} are {@code 0}.
         
    */
        public static ByteBuf directBuffer(int initialCapacity, int maxCapacity) {
            if (initialCapacity == 0 && maxCapacity == 0) {
                return EMPTY_BUFFER;
            }
            return new DirectByteBuf(initialCapacity, maxCapacity);
        }
        /**
         * Creates a new big-endian buffer which wraps the sub-region of the
         * specified {
    @code array}.  A modification on the specified array's
         * content will be visible to the returned buffer.
         
    */
        public static ByteBuf wrappedBuffer(byte[] array, int offset, int length) {
            if (length == 0) {
                return EMPTY_BUFFER;
            }
            if (offset == 0 && length == array.length) {
                return wrappedBuffer(array);
            }
            return new SlicedByteBuf(wrappedBuffer(array), offset, length);
        }  
        /**
         * Returns a new big-endian composite buffer with no components.
         
    */
        public static CompositeByteBuf compositeBuffer(int maxNumComponents) {
            return new DefaultCompositeByteBuf(maxNumComponents);
        } 
        /**
         * Creates a read-only buffer which disallows any modification operations
         * on the specified {
    @code buffer}.  The new buffer has the same
         * {
    @code readerIndex} and {@code writerIndex} with the specified
         * {
    @code buffer}.
         
    */
        public static ByteBuf unmodifiableBuffer(ByteBuf buffer) {
            if (buffer instanceof ReadOnlyByteBuf) {
                buffer = ((ReadOnlyByteBuf) buffer).unwrap();
            }
            return new ReadOnlyByteBuf(buffer);
        }


    通過Unpooled創(chuàng)建ByteBuf對(duì)象:

    ByteBuf heapBuffer    = Unpooled.buffer(128);

    ByteBuf directBuffer  = Unpooled.directBuffer(256);

    ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(new byte[128], new byte[256]);

     

    ByteBuf的類型

    Netty 4.0中,ByteBuf有以下幾種類型,分別是HeapByteBuf,WrappedByteBuf,DirectByteBuf,CompositeByteBuf。 HeapByteBufUnpooled類中是默認(rèn)的ByteBuf類型,通過Unpooled.buffer()取得。某人的緩沖器大小是256字節(jié)。

    WrappedByteBuf用于包裝一個(gè)字節(jié)數(shù)組或者一個(gè)ByteBuf,通過Unpooled.wrappedBuffer(byte[] array)或者Unpooled.wrappedBuffer(ByteBuf bytebuf)取得。

    DirectByteBufNIO的基本緩存器。

    CompositeByteBuf是一個(gè)組合緩沖器,將多個(gè)ByteBuf對(duì)象組合在同一個(gè)緩沖器中。

    具體看如下代碼:

    public class ByteBufTypeDemo {
          public static void main(String[] args){
               byte[] byteArrayA = {1, 2};
               byte[] byteArrayB = {3, 4};
              
               ByteBuf heapBuffer = Unpooled.buffer();
               System.out.println("/***********Heap ByteBuf***************/");
               System.out.println("Default Byte Order: " + heapBuffer.order());
               System.out.println("Default Heap Buffer Capacity: " + heapBuffer.capacity());
               System.out.println();
               System.out.println();
              
               ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteArrayA);
               System.out.println("/***********Wrapped ByteBuf***************/");
               for(int i = 0; i < wrappedBufferA.writerIndex(); i++){
                     System.out.println(wrappedBufferA.getByte(i));
               }
               System.out.println();
               System.out.println();
              
               ByteBuf wrappedBufferB = Unpooled.wrappedBuffer(byteArrayB);
               ByteBuf compositeByteBuf = Unpooled.compositeBuffer().addComponent(wrappedBufferA).addComponent(wrappedBufferB);
               Iterator<ByteBuf> compositeIterator = ((CompositeByteBuf)compositeByteBuf).iterator();
               System.out.println("/***********Composite ByteBuf***************/");
               while(compositeIterator.hasNext()){
                     ByteBuf tempBuf = compositeIterator.next();
                     for(int i = 0; i < 2;i++){
                          System.out.println(tempBuf.getByte(i));
                     }
               }
               System.out.println();
               System.out.println();
     
               System.out.println("/***********Direct ByteBuf***************/");
               ByteBuf directByteBuf = (DirectByteBuf)Unpooled.directBuffer();
               System.out.println("Has NIO Buffer? " + directByteBuf.hasNioBuffer());
               System.out.println();
               System.out.println();
               System.out.println("/*****************End*********************/");
          }
    }

     

     

    參考引用:http://baike.baidu.com/view/2368412.htm

     

    備注:因?yàn)楣P者開始寫Netty源碼分析的時(shí)候,Netty 4.0還是處于Alpha階段,之后的API可能還會(huì)有改動(dòng),筆者將會(huì)及時(shí)更改。使用開源已經(jīng)有好幾年的時(shí)間了,一直沒有時(shí)間和精力來具體研究某個(gè)開源項(xiàng)目的具體實(shí)現(xiàn),這次是第一次寫開源項(xiàng)目的源碼分析,如果文中有錯(cuò)誤的地方,歡迎讀者可以留言指出。對(duì)于轉(zhuǎn)載的讀者,請(qǐng)注明文章的出處。

    希望和廣大的開發(fā)者/開源愛好者進(jìn)行交流,歡迎大家的留言和討論。



    -----------------------------------------------------
    Silence, the way to avoid many problems;
    Smile, the way to solve many problems;

    posted on 2012-11-27 11:34 Chan Chen 閱讀(13502) 評(píng)論(2)  編輯  收藏 所屬分類: Netty

    評(píng)論

    # re: Netty 4.0 源碼分析(八):Netty 4.0中的io.netty.buffer包[未登錄] 2013-01-12 14:03

    把這一套看完了,Netty的常用API作用及用法我基本上都清楚,灰常謝謝?。?nbsp; 回復(fù)  更多評(píng)論   

    # re: Netty 4.0 源碼分析(八):Netty 4.0中的io.netty.buffer包 2015-12-10 18:16 tracie

    請(qǐng)問一下你的圖是用什么工具畫的?  回復(fù)  更多評(píng)論   

    主站蜘蛛池模板: 一区二区三区观看免费中文视频在线播放 | 亚洲精品**中文毛片| 色费女人18女人毛片免费视频| 亚洲av日韩av不卡在线观看| 亚洲国产电影av在线网址| 嫖丰满老熟妇AAAA片免费看| 精品成人免费自拍视频| 一级女性全黄久久生活片免费 | 久久免费区一区二区三波多野| 亚洲国产电影在线观看| 亚洲国产一成人久久精品| 四虎永久免费地址在线网站| 亚洲成在人线aⅴ免费毛片| 99在线热视频只有精品免费| 中文无码日韩欧免费视频| 黄色毛片免费在线观看| 亚洲GV天堂GV无码男同| 亚洲一区中文字幕在线电影网 | AAA日本高清在线播放免费观看| 一进一出60分钟免费视频| 亚洲精品**中文毛片| 久久精品国产亚洲AV麻豆网站 | 日本免费A级毛一片| 51午夜精品免费视频| 无码精品人妻一区二区三区免费| 亚洲国产成人久久综合| 亚洲欧洲无码一区二区三区| 亚洲欧洲自拍拍偷午夜色无码| 曰批全过程免费视频播放网站| 日韩精品免费在线视频| 污污网站免费观看| 91香蕉国产线观看免费全集| 最近中文字幕大全免费版在线 | 亚洲av鲁丝一区二区三区| 亚洲国产精品无码一线岛国| 国产亚洲综合色就色| 亚洲av无码一区二区乱子伦as| 国产美女无遮挡免费视频| 女人18特级一级毛片免费视频| 24小时日本在线www免费的| 午夜一级毛片免费视频|