NIO简介及三大组件

一、简介

  1. 用于完成数据的传输
  2. BIO - BlockingIO - 同步式阻塞式IO
  3. NIO - NonBlockingIO - 同步式非阻塞式IO - JDK1.4出现的
  4. NIO三大组件:Buffer - 缓冲区,Channel - 通道,Selector - 选择器

二、NIO与BIO的比较

  1. NIO是非阻塞的,BIO是阻塞的,所以效率上NIO要高一点
  2. BIO完成一次读写过程要产生大量的流对象 - 是单向的;NIO完成双向传输,因此可以减少流的创建数量
  3. 一对一的连接:客户端的每一个请求在服务器端都必须有一个线程与之对应;NIO所使用的一对多的机制:可以利用一个或者少量线程去处理大量的请求
  4. 连接一旦建立,即使没有后续操作,这个客户端依然会占用服务器端的线程;NIO会建立选择机制,会根据客户端的请求来确定是否分配线程

三.buffer缓冲区
1、简介

  1. 用于存储数据
  2. 底层是基于数组来进行存储
  3. 只能存储基本类型
  4. 针对八种基本类型分别提供了对应的缓冲区类,但是没有boolean类型:ByteBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBuffer,DoubleBuffer,CharBuffer
  5. 重要的位置:mark <= position <= limit <= capacity
    a. capacity:容量位.指定缓冲区的容量/大小
    b. limit:限制位.用于限定操作位所能达到的最大下标.缓冲区刚刚创建的时候,限值位和容量位是一样的
    c. position:操作位.类似于数组中的下标,用于指向要读写的位置.缓冲区刚刚创建的时候,操作位是指向第0位的
    d. mark:标记位.标记位默认是不启用的
  6. 重要的操作:
    a. flip:翻转缓冲区
    b. reset:重置缓冲区
    c. rewind:重绕缓冲区
    d. clear:清空缓冲区

四 channel 通道
一、简介

  1. 用于进行数据的传输
  2. 面向缓冲区进行操作
  3. 可以进行双向传输
  4. 针对文件的通道:FileChannel
    针对网络的通道:
    UDP - DatagramChannel
    TCP - SocketChannel ServerSocketChannel
  5. 通道默认是阻塞的,手动设置为非阻塞

二、客户端

public class SocketChannelDemo {
public static void main(String[] args) throws IOException {
// 获取客户端的通道
SocketChannel sc = SocketChannel.open();
 // 手动设置为非阻塞
sc.configureBlocking(false);
// 发起连接
// 而一旦设置为非阻塞,那么无论连上与否都会继续往下走
sc.connect(new InetSocketAddress("localhost", 8070));
// 进行判断,需要判断是否真正连接上
while (!sc.isConnected())
// 试图建立连接,如果多次连接之后依然没有连上
// 则认为这个连接是无效的,就会抛出异常
sc.finishConnect();
// 写数据
sc.write(ByteBuffer.wrap("hello server".getBytes()));
// 关闭
sc.close();
	 }
}

三、服务器端

public class ServerSocketChannelDemo {
public static void main(String[] args) throws IOException {
// 开启服务器端的通道
ServerSocketChannel ssc = ServerSocketChannel.open();
// 绑定端口
ssc.bind(new InetSocketAddress(8070));
// 设置为非阻塞
ssc.configureBlocking(false);
// 接收连接
SocketChannel sc = ssc.accept();
// 判断连接是否接到
while (sc == null)
sc = ssc.accept();
// 读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
// 遍历缓冲区
buffer.flip();
System.out.println(
new String(buffer.array(), 0, buffer.limit()));
// 关闭
ssc.close();
 	}
}

五 selector 多路复用选择器
一、简介

  1. 针对有用的请求进行选择:accept、read、write
  2. 针对通道进行选择,要求通道必须是非阻塞的

二、服务器端

public class Server { 
public static void main(String[] args) throws IOException { 
// 开启服务器端的通道
ServerSocketChannel ssc = ServerSocketChannel.open();
// 绑定端口
ssc.bind(new InetSocketAddress(8070));
// 设置为非阻塞
ssc.configureBlocking(false);
// 开启选择器
Selector selc = Selector.open();
// 将通道注册到选择器上
ssc.register(selc, SelectionKey.OP_ACCEPT); 
while (true) {
// 进行选择
selc.select(); 
// 获取处理的事件
Set<SelectionKey> keys = selc.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while (it.hasNext()) {
// 获取单个事件
SelectionKey key = it.next();
// 可能是accept
if (key.isAcceptable()) {
ServerSocketChannel sscx = (ServerSocketChannel) key.channel();
SocketChannel sc = sscx.accept();
System.out.println("连接成功~~~");
// 设置非阻塞
sc.configureBlocking(false);
// 注册一个read事件
sc.register(selc, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
}
// 可能是read
if (key.isReadable()) {   
// 先从事件身上获取到通道
SocketChannel sc = (SocketChannel) key.channel();
// 读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.limit()));   
// 获取通道身上的所有的事件
sc.register(selc, key.interestOps() ^ SelectionKey.OP_READ);  
}
// 可能是write
if (key.isWritable()) {     
// 获取通道
SocketChannel sc = (SocketChannel) key.channel();     
sc.write(ByteBuffer.wrap("hi client~~~".getBytes()));  
sc.register(selc, key.interestOps() ^ SelectionKey.OP_WRITE);
}   
it.remove();
			}
		}	     
	} 
}

猜你喜欢

转载自blog.csdn.net/yang134679/article/details/93381081