NIO个人日志


    NIO基础组件:


        Buffer:
            属性:
                Position(位置):初始值为0,读/写一个值自动加一。
                Limit:
                    写:和容量值一样大。
                    读:Buffer实际数据大小。
                Capacity:缓冲区容量。
            方法:
                (1)allocate (int capacity):快速实例化一个Buffer。
                   xxxBuffer buf = new xxxBuffer(1024);
                
                (2)public static ByteBuffer warp (Byte[]array){...}
                
                (3)mark()&reset()
                    mark(): mark=position,把读到的位置存下来。
                    reset():position=mark,读值进度返回到原来存的地方。
                    
                (4)rewind()&clear()&compact()
                    rewind():position=0,读写进度回到0。
                    clear():重新初始化一下Buffer。
                    compact():position到limit之间的数据左移,在这基础上进行开始写。
                    


        Channel:

  • 属性:

                FileChannel:文件通道,用于文件的读写。
                DatagramChannel:UDP的连接,接收,发送。
                SocketChannel:TCP客户端,连接通道。
                ServerSocketChannel:TCP服务端,监听端口请求。

  • 写操作:

                 Buffer  <-------  xxxChannel:数据从Channel读到Buffer,进行操作。

                 方法:Channel.read(buffer);

  • 读操作:

                 Buffer------->    xxxChannel:数据从Buffer写到Channel。

                 方法:Channel.write(buffer);


        Seletor(选择器/多路复用器):

                register();第二个参数

  • selectionkey.OP_READ

              值是1,通道里有数据可以进行读取。

扫描二维码关注公众号,回复: 6789904 查看本文章
  • selectionkey.OP_WRITYE

              值是4,可以向通道里写数据。

  • selectionkey.OP_CONNECT

​​​​​​​             值是8,成功建立TCP连接。

  • selectionkey.OP_ACCEP

​​​​​​​            值是16,接受TCP连接。

               selector.select();     判断register()是否有事情发生。返回的int值代表事情的数量。

猜你喜欢

转载自blog.csdn.net/China_C_boss/article/details/84256402