Java NIO是在jdk1.4开始使用的,它既能够说成“新IO”,也能够说成非阻塞式I/O。下面是java NIO的工做原理:java
由一个专门的线程来处理全部的IO事件,并负责分发。api
事件驱动机制:事件到的时候触发,而不是同步的去监视事件。服务器
线程通信:线程之间经过wait,notify等方式通信。保证每次上下文切换都是有意义的。减小无谓的线程切换。socket
阅读过一些资料以后,下面贴出我理解的java NIO的工做原理图:this
注:每一个线程的处理流程大概都是读取数据,解码,计算处理,编码,发送响应。编码
Java NIO的服务端只需启动一个专门的线程来处理全部的IO事件,这种通讯模型是怎么实现的呢?呵呵,咱们一块儿来探究它的奥秘吧。java NIO采用了双向通道(channel)进行数据传输,而不是单向流(stream),在通道上能够注册咱们感兴趣的事件。一共有如下四种事件:.net
事件名 |
对应值 |
服务端接收客户端链接事件 |
SelectionKey.OP_ACCEPT(16) |
客户端链接服务端事件 |
SelectionKey.OP_CONNECT(8) |
读事件 |
SelectionKey.OP_READ(1) |
写事件 |
SelectionKey.OP_WRITE(4) |
服务端和客户端各自维护一个管理通道的对象,咱们称之为selector,该对象能检测一个或多个通道(channel)上的事件。咱们以服务端为例,若是服务端的selector上注册了读事件,某时刻客户端给服务端送了一些数据,阻塞I/O这时会调用read()方法阻塞地读取数据,而NIO的服务端会在selector中添加一个读事件。服务端的处理线程会轮询地访问selector,若是访问selector时发现有感兴趣的事件到达,则处理这些事件,若是没有感兴趣的事件到达,则处理线程会一直阻塞直到感兴趣的事件到达为止。下面是我理解的java NIO的通讯模型示意图:线程
为了更好地理解java NIO,下面贴出服务端和客户端的简单代码实现:code
服务端:server
package 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() *会一直阻塞。 */ serverChannel.register(selector, SelectionKey.OP_ACCEPT); } /* * 采用轮询的方式监听selector上是否有须要处理的事件,若是有,则进行处理 * @throws IOException */ public void listen() throws IOException { System.out.println("服务端启动成功!"); //轮询访问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.isAcceptable()){ ServerSocketChannel server = (ServerSocketChannel)key.channel(); //得到和客户端链接的通道 SocketChannel channel = server.accept(); //设置成非阻塞 channel.configureBlocking(false); //在这里能够给客户端发送信息哦 channel.write(ByteBuffer.wrap(new String("1234567890").getBytes())); //在和客户端链接成功以后,为了能够接收到客户端的信息,须要给通道设置读权限 channel.register(this.selector, SelectionKey.OP_READ); }else if(key.isReadable()){ read(key); } } } } /* * 处理读取客户端发来的信息的事件 * @param key * @throws IOException */ 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);//将消息回送给客户端 } public static void main(String[] args) throws IOException { NIOServer server = new NIOServer(); server.initServer(8080); server.listen(); } }
客户端:
package 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,链接的服务器的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(this.selector, SelectionKey.OP_CONNECT); } /* * 采用轮询的方式监听selector上是否有须要处理的事件,若是有,则进行处理。 * @throws IOException */ public void listen() throws IOException{ //轮询访问selector while(true){ /* * 选择一组能够进行I/O操做的事件,放在selector中,客户端的该方法不会阻塞, * 这里和服务端的方法不同,查看api注释能够知道,当至少一个通道被选中时, * selector的wakeup方法被调用,方法返回,而对于客户端来讲,通道一直是被选中的 */ 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("abcdefg").getBytes())); //在和服务端链接成功以后,为了能够接收到服务端的信息,须要给通道设置读的权限 channel.register(this.selector, SelectionKey.OP_READ); //得到了可读的事件 } else if(key.isReadable()){ read(key); } } } } public void read(SelectionKey key) throws IOException{ 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); } public static void main(String[] args) throws IOException{ NIOClient client = new NIOClient(); client.initClient("localhost", 8080); client.listen(); } }