java nio学习:缓冲区、通道和选择器

java nio中引入了缓冲区,缓冲区中的数据可以写入通道,也可以从通道中读取数据到缓冲区。nio中的缓冲区就是对数组的简单封装,缓冲区有读模式和写模式,缓冲区的属性有容量(capacity)、限制(limit)、位置(position),容量表示数组的大小,限制表示第一个不能读写的位置,位置表示读写索引的位置。

新申请一个1024字节的缓冲区

ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println(buf);//pos=0 lim=1024 cap=1024
向缓冲区中放入两字节数据

ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte)1);
buf.put((byte)2);
System.out.println(buf);//pos=2 lim=1024 cap=1024
翻转缓冲区,缓冲区从读模式变为写模式,pos为缓冲区的读位置,lim为读数据的上界

ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte)1);
buf.put((byte)2);
buf.flip();
System.out.println(buf);//pos=0 lim=2 cap=1024
调用get()可获得缓冲区中的数据,hasRemaining()可检查数据是否读取完
while(buf.hasRemaining())
	System.out.println(buf.get());
System.out.println(buf);//pos=2 lim=2 cap=1024

clear()可清空缓冲区,使其为读通道数据做好准备

buf.clear();
System.out.println(buf);//pos=0 lim=1024 cap=1024

java nio抽象出通道的概念,可以向通道中写入数据或从通道中读取数据

ServerSocketChannel用于监听和接收连接,可通过调用ServerSocketChannel的open()方法创建,接着绑定本地地址就可监听连接,accept()方法可创建新的连接

ServerSocketChannel acceptor = ServerSocketChannel.open();
acceptor.socket().bind(new InetSocketAddress(80));
SocketChannel channel = acceptor.accept();
 
  

 
  

SocketChannel表示网络连接,用于读写数据。

ByteBuffer buf = ByteBuffer.allocate(1024);
while( (channel.read(buf)) > 0 )
{
	buf.flip();
					
	channel.write(buf);
					
	buf.clear();
}				
channel.close();

java nio通过选择器,可以同时监视多个通道上是否有事件发生。一个通道可以在选择器上注册接受、可读、可写和连接事件,当事件发生时,选择器select调用就会返回,可以通过检查返回的选择键获取事件信息

选择器可通过open()方法创建,接着就可以在上面注册关心的事件

Selector selector = Selector.open();
acceptor.register(selector, SelectionKey.OP_ACCEPT);//注册接受事件
channel.register(selector, SelectionKey.OP_READ);//注册读事件

 调用select()方法就可以等待事件的发生,接着处理发生的事件 
  

selector.select();				
Set keys = selector.selectedKeys();
				
for (SelectionKey key : keys)
{				
	if(key.isAcceptable())
	{
		...
	}
	else if(key.isReadable())
	{
		...
	}
	...
}
keys.clear();


 
  







你可能感兴趣的:(java)