java NIO实现基本原理

 NIO的工作原理:

1、由一个专门的线程来处理所有的 IO 事件,并负责分发。

2、事件驱动机制:事件到的时候触发,而不是同步的去监视事件

3、线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的线程切换

java NIO采用了双向通道(channel)进行数据传输,而不是单向的流(stream),在通道上可以注册我们感兴趣的事件。一共有以下四种事件:

事件名 对应值
服务端接收客户端连接事件 SelectionKey.OP_ACCEPT
客户端连接服务端事件 SelectionKey.OP_CONNECT(8)
读事件 SelectionKey.OP_READ(1)
写事件 SelectionKey.OP_WRITE(4)

服务端和客户端各自维护一个管理通道的对象,我们称之为selector,该对象能检测一个或多个通道 (channel) 上的事件。我们以服务端为例,如果服务端的selector上注册了读事件,某时刻客户端给服务端发送了一些数据,阻塞I/O这时会调用read()方法阻塞地读取数据,而NIO的服务端会在selector中添加一个读事件。服务端的处理线程会轮询地访问selector,如果访问selector时发现有感兴趣的事件到达,则处理这些事件,如果没有感兴趣的事件到达,则处理线程会一直阻塞直到感兴趣的事件到达为止。

简单代码实现

服务端

package com.current.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOServer {
    //通道管理器
    private Selector selector;

    /**
     * 获得一个serverSocket通道,并对该通道做一些初始化的工作
     *
     * @param port 绑定的端口号
     * @throws IOException
     */
    public void initServer(int port) throws IOException {
        //获得一个ServerSocket通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        //设置为非阻塞
        serverChannel.configureBlocking(false);
        //将该通道对应的ServerSocket绑定到port端口
        serverChannel.socket().bind(new InetSocketAddress(port));
        //获得一个通道管理器
        this.selector = Selector.open();
        //将通道管理器和通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件后
        //当该事件到达时,selector.select()会返回,如果该事件没有调用selector.select会一直阻塞
        //reark:当有客户端连接8000这个端口时,将这个chanel上的所有初始连接都设置为OP_ACCEPT
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    /**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     */
    public void listen() throws IOException {
        System.out.println("服务端启动成功");
        //轮询访问selector
        while (true) {
            //当注册事件到达时(有新的连接或连接传输数据通过8000端口),方法返回,否则,该方法会一直阻塞,调用操作系统的底层东西
            selector.select();
            //select方法返回后会返回一个selectKeys
            //获得selector中选中项的迭代器,选中的项为注册事件
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                //channel绑定的key
                SelectionKey key = (SelectionKey) ite.next();
                //删除已选的key,以防重复处理
                ite.remove();
                //客户端请求连接事件
                //第一次客户端创建连接事件会将是accept,即init里面的OP_ACCEPT
                if (key.isAcceptable()) {
                    handleAccept(key);
                } else if (key.isReadable()) {
                    handleRead(key);
                }
            }
        }
    }

    /**
     * 处理可读的服务器通道
     *
     * @param key SelectionKey
     * @throws IOException
     */
    public void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        //获得和客户端的连接通道
        SocketChannel channel = server.accept();
        //设置为非阻塞的
        channel.configureBlocking(false);
        //telnet输出了这句话表示已经和服务器连接上了
        channel.write(ByteBuffer.wrap("send message to server:".getBytes()));
        //在和客户端连接成功后,为了可以接受客户端的信息,需要给通道设置读的权限
        channel.register(this.selector, SelectionKey.OP_READ);
    }

    public void handleRead(SelectionKey key) throws IOException {
        //服务器可读消息,得到事件发生的Socket通道
        SocketChannel channel = (SocketChannel) key.channel();
        //创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("服务端收到消息:" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap("ok".getBytes());
        //将消息会送给客户端
        channel.write(outBuffer);
    }

    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.initServer(8000);
        server.listen();
    }
}

客户端

package com.current.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {
    //通道管理器
    private Selector selector;

    /**
     * 获得一个socket通道,并对该通道做一些初始化的工作
     *
     * @param ip
     * @param port
     * @throws IOException
     */
    public void initClient(String ip, int port) throws IOException {
        //获得一个Socket通道
        SocketChannel channel = SocketChannel.open();
        //设置通道为非租塞
        channel.configureBlocking(false);
        //获得一个通道管理器
        this.selector = Selector.open();
        //客户端连接服务器,其实并没有实现连接,需要listen()方法中调
        // 用channel.finishConnect();才完成连接
        channel.connect(new InetSocketAddress(ip, port));
        //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    public void listen() throws IOException {
        //轮询访问selector
        while (true) {
            //阻塞在这里直到消息到达
            selector.select();
            //获得Selector中选中的迭代器
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                //删除已选的key,以防重复处理
                ite.remove();
                //连接事件发生
                if (key.isConnectable()) {
                    //获得连接的通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    //如果正在连接,则完成连接
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    //设置成非阻塞的
                    channel.configureBlocking(false);
                    //在这里可以给服务器发送消息哦
                    channel.write(ByteBuffer.wrap(new String("向服务器发送了一条消息").getBytes()));
                    channel.register(this.selector, SelectionKey.OP_READ);
                    //获得了可读事件
                } else if (key.isReadable()) {
                    read(key);
                }
            }
        }
    }

    public void read(SelectionKey key) throws IOException {
        //服务器可读消息,得到事件发生的Socket通道
        SocketChannel channel = (SocketChannel) key.channel();
        //创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(10);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("服务端收到消息:" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        //将消息会送给客户端
        channel.write(outBuffer);
    }

    /**
     * 启动客户端测试
     *
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("localhost", 8000);
        client.listen();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38829588/article/details/105499159