一、NIO 非阻塞网络编程原理分析
NIO 非阻塞网络编程相关的(Selector、SelectionKey、ServerScoketChannel 和 SocketChannel)关系梳理图
对上图的说明:
- 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel。
- Selector 进行监听 select 方法,返回有事件发生的通道的个数。
- 将 socketChannel 注册到 Selector 上,register(Selector sel, int ops),一个 Selector 上可以注册多个 SocketChannel。
- 注册后返回一个 SelectionKey,会和该 Selector 关联(集合)。
- 进一步得到各个 SelectionKey(有事件发生)。
- 在通过 SelectionKey 反向获取 SocketChannel,方法 channel()。
- 可以通过得到的 channel,完成业务处理。
二、案例
- 编写一个 NIO 入门案例,实现服务器端和客户端之间的数据简单通讯(非阻塞)
-
服务器端
public class NIOServer {public static void main(String[] args) throws IOException {//创建ServerSocketChannel -> ServerSocketServerSocketChannel serverSocketChannel = ServerSocketChannel.open();//得到一个 selector 对象Selector selector = Selector.open();//绑定一个端口6666, 在服务器端监听serverSocketChannel.socket().bind(new InetSocketAddress(6666));// 设置为非阻塞serverSocketChannel.configureBlocking(false);//把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPTserverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1//循环等待客户端连接while (true) {//这里我们等待1秒,如果没有事件发生, 返回if (selector.select(1000) == 0) { // 没有事件发生System.out.println("服务器等待了1秒,无连接");continue;}//如果返回的>0, 就获取到相关的 selectionKey集合//1.如果返回的>0, 表示已经获取到关注的事件//2. selector.selectedKeys() 返回关注事件的集合// 通过 selectionKeys 反向获取通道Set<SelectionKey> selectionKeys = selector.selectedKeys();System.out.println("selectionKeys 数量 = " + selectionKeys.size());//遍历 Set<SelectionKey>, 使用迭代器遍历Iterator<SelectionKey> iterator = selectionKeys.iterator();while (iterator.hasNext()) {// 获取到 selectionKeySelectionKey key = iterator.next();// 根据 key 对应的通道发生的事件做相应的处理if (key.isAcceptable()) { //如果是 OP_ACCEPT, 有新的客户端连接//该该客户端生成一个 SocketChannelSocketChannel socketChannel = serverSocketChannel.accept();System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode());//将 SocketChannel 设置为非阻塞socketChannel.configureBlocking(false);//将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel//关联一个BuffersocketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));// 下面这行代码小提示 selector.selectedKeys() 和 selector.keys() 不一样// selector.selectedKeys() 返回有事件的 SelectionKey// selector.keys() 返回所有 SelectionKeySystem.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4..}if (key.isReadable()) { //发生 OP_READSocketChannel channel = (SocketChannel) key.channel();// 原来是监听 read事件的,可以改为监听 write事件// key.interestOps(SelectionKey.OP_WRITE);// 获取到该 channel 关联的 bufferByteBuffer buffer = (ByteBuffer) key.attachment();channel.read(buffer);System.out.println("form 客户端 :" + new String(buffer.array()));}//手动从集合中移动当前的selectionKey, 防止重复操作iterator.remove();}}}}
客户端
public class NIOClient {public static void main(String[] args) throws IOException {// 得到一个网络通道SocketChannel socketChannel = SocketChannel.open();//设置非阻塞socketChannel.configureBlocking(false);//提供服务器端的ip 和 端口InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);//连接服务器if(!socketChannel.connect(inetSocketAddress)){while (!socketChannel.finishConnect()){System.out.println("因为连接需要时间,客户端不会阻塞,可以做其它工作..");}}//...如果连接成功,就发送数据String str = "hello, supkingx";// Wraps a byte array into a buffer.ByteBuffer buffer = ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));//发送数据,将 buffer 数据写入 channelsocketChannel.write(buffer);System.in.read();}}
三、SelectionKey
SelectionKey,表示 Selector 和网络通道的注册关系,共四种:
- int OP_ACCEPT:有新的网络连接可以 accept,值为 16
- int OP_CONNECT:代表连接已经建立,值为 8
- int OP_READ:代表读操作,值为 1
- int OP_WRITE:代表写操作,值为 4
- 源码中对应
public static final int OP_READ = 1 << 0;public static final int OP_WRITE = 1 << 2;public static final int OP_CONNECT = 1 << 3;public static final int OP_ACCEPT = 1 << 4;
- SelectionKey 相关方法

这里面的方法在 上面的 案例 中悉数用到了。
四、ServerSocketChannel
- ServerSocketChannel 在服务器端监听新的客户端 Socket 连接,负责监听,不负责实际的读写操作
- 相关方法如下

这里面的方法在 上面的 案例 中悉数用到了。
五、SocketChannel
- SocketChannel,网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区。
- 相关方法如下

这里面的方法在 上面的 案例 中悉数用到了。
