java_NIO小结

Channel and Buffer

一:总体

Channel 和 buffer 是 NIO 是两个最基本的数据类型抽象。


数据源--》通道(read)--》Buffer-->通道(write)-->数据汇


Buffer:

  是一块连续的内存块。

  是 NIO 数据读或写的中转地。

Channel:

  数据的源头或者数据的目的地

  用于向 buffer 提供数据或者读取 buffer 数据 ,buffer 对象的唯一接口。

  异步 I/O 支持

数据从channel(源头)读入buffer中:channel-->buffer

数据从buffer写入channel(目的地)中:buffer->channel

主要的channel:

FileChannel,DatagramChannel,SocketChannel,ServerSocketChannel

主要Buffer:

ByteBuffer,CharBuffer,DoubleBuffer,FloatBuffer

二:Buffer的数据读写步骤

1写入数据到buffer

2调用flip方法

3从Buffer中读取数据

4调用clear()方法


向Buffer中写入数据:

1)从channel写入Buffer:inChannel.read(buffer)

2)通过buffer的put方法自己放入数据

从Buffer中读取数据:

1)从Buffer读取数据到Channel:outChannel.write(buffer)

2)使用buffer的get()方法


三:Channel

1 FileChannel:一个连接到文件的通道,可以通过它来读写文件

2 SocketChannel:一个连接到TCP网络套接字的通道

1)打开一个SocketChannel并连接到互联网上的某台服务器

SocketChannel sc = SocketChannel.open();

sc.connect(new InetSocketAddress(""));

2)当一个新的连接到达ServerSocketChannel时,会创建一个SocketChannel

3 ServerSocketChannel:一个可以监听新进来的TCP连接的通道

ServerSocketChannel c = ServerSocketChannel.open();

c.socket.bind(new InetSocketAddress(""));

while(true){

  SocketChannel sc = c.accept();

}

Selector:

能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写时间做好准备的组件,这样一个单独的线程可以管理多个Channel,从而管理多个网路连接

允许单线程中处理多个channel(例如聊天服务器,应用打开了多个连接,但每一个的流量都很低)

Thread->Selector->Channel1

                                ->Channel2

                                ->Channel3


1创建:Selector.open();

2 向selector注册通道

  channel.configurBlocking(false);

  channel.register(selector,SelectionKey.OP_READ);

3 使用selector选择通道

Set selectedKeys = selector.selectedKeys();

Iterator keys = selectedKeys.iterator();

while(keys.hasNext()){

  SelectionKey key = keys.next();

  ...

}


Scatter/Gather

scatter:分散,从channel中读取数据,并写入多个buffer中

Gather:聚集,将数据从多个buffer中写入到同一个channel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值