Java NIO原理图文分析

来源:互联网 发布:佛山市软件行业协会 编辑:程序博客网 时间:2024/05/21 19:22

一.java NIO 和阻塞I/O的区别
     1. 阻塞I/O通信模型
     2. java NIO原理及通信模型
二.java NIO服务端和客户端代码实现
 

具体分析: 

一.java NIO 和阻塞I/O的区别 

1. 阻塞I/O通信模型
 

假如现在你对阻塞I/O已有了一定了解,我们知道阻塞I/O在调用InputStream.read()方法时是阻塞的,它会一直等到数据到来时(或超时)才会返回;同样,在调用ServerSocket.accept()方法时,也会一直阻塞到有客户端连接才会返回,每个客户端连接过来后,服务端都会启动一个线程去处理该客户端的请求。阻塞I/O的通信模型示意图如下:

 

 

如果你细细分析,一定会发现阻塞I/O存在一些缺点。根据阻塞I/O通信模型,我总结了它的两点缺点:
1. 当客户端多时,会创建大量的处理线程。且每个线程都要占用栈空间和一些CPU时间

2. 阻塞可能带来频繁的上下文切换,且大部分上下文切换可能是无意义的。

在这种情况下非阻塞式I/O就有了它的应用前景。

2. 
java NIO原理及通信模型 

Java NIO是在jdk1.4开始使用的,它既可以说成“新I/O”,也可以说成非阻塞式I/O。下面是java NIO的工作原理:

1. 由一个专门的线程来处理所有的 IO 事件,并负责分发。 
2. 事件驱动机制:事件到的时候触发,而不是同步的去监视事件。 
3. 线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的线程切换。 

阅读过一些资料之后,下面贴出我理解的java NIO的工作原理图:

 

 

(注:每个线程的处理流程大概都是读取数据、解码、计算处理、编码、发送响应。)

Java NIO的服务端只需启动一个专门的线程来处理所有的 IO 事件,这种通信模型是怎么实现的呢?呵呵,我们一起来探究它的奥秘吧。java NIO采用了双向通道(channel)进行数据传输,而不是单向的流(stream),在通道上可以注册我们感兴趣的事件。一共有以下四种事件:

 

事件名对应值服务端接收客户端连接事件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的通信模型示意图:

 


结合代码理解:

服务器端代码

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;
import java.util.Set;


public class NioServerTest implements Runnable{
private final int BLOCK = 4096;
/*发送数据缓冲区*/
private final ByteBuffer sendBuffer = ByteBuffer.allocate(BLOCK);
/*接受数据缓冲区*/
private final ByteBuffer receiveBuffer = ByteBuffer.allocate(BLOCK);
//通道管理器  
    private Selector selector;  
    
    private int flag;
    //初始化服务器配置
public void initServer(int port) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();//打开服务器管道,只能通过open方法获取,不能使用new创建
serverSocketChannel.configureBlocking(false);//设置为非阻塞
InetSocketAddress inetSocketAddress = new InetSocketAddress(port);//创建连接管道端口地址
serverSocketChannel.socket().bind(inetSocketAddress);//给serverSocket管道的socket绑定端口
selector = Selector.open();//打开通道管理器
/*
将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,  
当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
        */
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
System.out.println("服务端启动成功!"); 
}
/** 
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 
     * @throws IOException 
     */  
public void listion() throws IOException{
System.out.println("服务端监听开始!"); 
// 轮询访问selector
while(true){
//当注册的事件到达时,方法返回;否则,该方法会一直阻塞  
selector.select();
/*
 前面说注册器Seclector要监听ON_ACCEPT事件现在事件来了  需要服务端做相应处理了
           这里的处理方式是 启动一个 SocketChannel对象来处理客户端的这个连接,这里的处理
           是给当前的这个事件key绑定一个SocketChannel对象 ,告诉selector 如有ON_READ事件
           进来就用此SocketChannl来处理 
        */
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
while(it.hasNext()){
SelectionKey selectionKey = it.next();
//删除已选的key,以防重复处理  
                it.remove();  
                handleClientRequest(selectionKey);
}
flag++;
}
}
public void handleClientRequest(SelectionKey selectionKey) throws IOException{
ServerSocketChannel serverChannel = null;
SocketChannel clientChannel = null;
String receiveText;
String sendText;
int count;
if(selectionKey.isAcceptable()){//客户端请求连接事件
try {
//启动服务器的一个channel对象对某个事件进行处理,这个channel对象代表客户端的连接
serverChannel = (ServerSocketChannel)selectionKey.channel();
clientChannel = serverChannel.accept();//处于阻塞状态
clientChannel.configureBlocking(false);//设置成非阻塞
sendText = "客户端你可以连我了....................";
sendBuffer.clear();
sendBuffer.put(sendText.getBytes());
sendBuffer.flip();
clientChannel.write(sendBuffer);
//在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
clientChannel.register(selector, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}else if(selectionKey.isReadable()){//客户端请求读事件
clientChannel = (SocketChannel)selectionKey.channel();
receiveBuffer.clear();//在读取客户端的数据要清空缓冲区,把缓冲区的position设置为0,limit=capacity
count = clientChannel.read(receiveBuffer);
receiveText = new String(receiveBuffer.array(),0,count);
System.out.println("获取客户端的数据:" + receiveText + "-" + flag);
//为了可以向客户端发送数据,需要给通道设置写的权限。
clientChannel.register(selector, SelectionKey.OP_WRITE);
}else if(selectionKey.isWritable()){//客户端请求写事件
clientChannel = (SocketChannel)selectionKey.channel();
sendText = "客户端你好"+flag;
sendBuffer.clear();
sendBuffer.put(sendText.getBytes());
sendBuffer.flip();//在向客户端写数据之前,将缓冲区的position设置为0,limit=position未回复为0时的位置
clientChannel.write(sendBuffer);
clientChannel.register(selector, SelectionKey.OP_READ);
}
}
public void run() {
try {
listion();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
NioServerTest server = new NioServerTest();
server.initServer(8888);
new Thread(server).start();
}
}


客户端:

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;
import java.util.Set;
public class NioClientTest implements Runnable{
private final int BLOCK = 4096;
/*发送数据缓冲区*/
private final ByteBuffer sendBuffer = ByteBuffer.allocate(BLOCK);
/*接受数据缓冲区*/
private final ByteBuffer receiveBuffer = ByteBuffer.allocate(BLOCK);
private Selector selector;
private int flag = 0;
public void initClient() throws IOException{
InetSocketAddress hostAddress = new InetSocketAddress("localhost",8888);//连接服务器地址
SocketChannel socketChannel = SocketChannel.open();//打开通道
socketChannel.configureBlocking(false);//设置为非阻塞
//打开通道管理器
selector = Selector.open();
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。  
socketChannel.register(selector, SelectionKey.OP_CONNECT);
// 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调用socketChannel.finishConnect();才能完成连接  
socketChannel.connect(hostAddress);
}
public void listen() throws IOException{
System.out.println("客户端监听开始-" + flag);
while(true){//通道管理器selector对通道进行轮询操作
selector.select();//阻塞状态
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
iterator.remove();
handleServerResult(selectionKey);
}
keys.clear();
flag++;
}
}
public void handleServerResult(SelectionKey selectionKey) throws IOException{
String sendText;
String receiveText;
int count;
SocketChannel socketChannel;
if(selectionKey.isConnectable()){
socketChannel = (SocketChannel)selectionKey.channel();
if(socketChannel.isConnectionPending()){//如果socket正在连接,则完成连接
socketChannel.finishConnect();
sendBuffer.clear();
sendText = "服务器你好,我连接上你了,有何指示"+flag;
sendBuffer.put(sendText.getBytes());
sendBuffer.flip();
socketChannel.write(sendBuffer);
}
socketChannel.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){
receiveBuffer.clear();
socketChannel = (SocketChannel)selectionKey.channel();
count = socketChannel.read(receiveBuffer);
receiveText = new String(receiveBuffer.array(),0,count);
System.out.println("接收到服务器的指示:"+receiveText + "-" + flag);
socketChannel.register(selector, SelectionKey.OP_WRITE);
}else if(selectionKey.isWritable()){
sendBuffer.clear();
socketChannel = (SocketChannel)selectionKey.channel();
sendText = "服务器你好,有何指示"+flag;
sendBuffer.put(sendText.getBytes());
sendBuffer.flip();
socketChannel.write(sendBuffer);
socketChannel.register(selector, SelectionKey.OP_READ);
}
}
public void run() {
try {
listen();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
NioClientTest client = new NioClientTest();
try {
client.initClient();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(client).start();
}

}

 


原始博客地址http://weixiaolu.iteye.com/blog/1479656

0 0
原创粉丝点击