Netty学习3-NIO详解

1 概念辨析

阻塞与非阻塞

阻塞:应用程序获取数据时,若网络传输数据很慢,程序就一直等到传输完毕为止。BIO面向流,当建立连接后传输流即同步阻塞。

非阻塞:应用程序可直接获取已准备好的的数据(如放在缓冲区中的数据)无需等待。NIO面向缓冲区,即同步非阻塞。

同步与异步

同步:应用程序直接参与IO读写操作,应用程序会阻塞在某一个方法上,直到数据准备就绪,或者采用轮询策略实时监测数据状态,若数据准备就绪就获取数据。

异步:所有的IO操作都交给OS处理,与应用程序没有直接关系,当OS完成了IO读写操作时会给应用程序发送通知,应用程序直接拿走数据即可。


2 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;

/**
 * NIO服务端
 */
public class NIOServer {
	
	// 通道管理器,相当于超级服务生,把门口迎接客人,服务客人的活都做了
	private Selector selector;

	/**
	 * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
	 * 
	 * @param port 绑定的端口号
	 */
	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上是否有需要处理的事件,如果有,则进行处理
	 */
	public void listen() throws IOException {
		System.out.println("服务端启动成功!");
		// 轮询访问selector
		while (true) {
			// 当注册的事件到达时,方法返回。否则,该方法会一直阻塞
			// C语言实现
			selector.select();
			// 获得selector中选中的项的迭代器,选中的项为注册的事件
			Iterator<?> ite = this.selector.selectedKeys().iterator();
			while (ite.hasNext()) {
				SelectionKey key = (SelectionKey) ite.next();
				// 删除已选的key,以防重复处理
				ite.remove();
				handler(key);
			}
		}
	}

	/**
	 * 处理请求
	 */
	public void handler(SelectionKey key) throws IOException {
		if (key.isAcceptable()) {
			// 客户端请求连接事件
			handlerAccept(key);
		} else if (key.isReadable()) {
			// 获得了可读的事件
			handelerRead(key);
		}
	}

	/**
	 * 处理连接请求
	 */
	public void handlerAccept(SelectionKey key) throws IOException {
		ServerSocketChannel server = (ServerSocketChannel) key.channel();
		// 获得和客户端连接的通道
		SocketChannel channel = server.accept();
		// 设置成非阻塞
		channel.configureBlocking(false);

		// 在这里可以给客户端发送信息哦
		System.out.println("新的客户端连接");
		// 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道注册读的事件
		channel.register(this.selector, SelectionKey.OP_READ);
	}

	/**
	 * 处理读的事件
	 */
	public void handelerRead(SelectionKey key) throws IOException {
		// 服务器可读取消息:得到事件发生的Socket通道
		SocketChannel channel = (SocketChannel) key.channel();
		// 创建读取的缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		int read = channel.read(buffer);
		if (read > 0) {
			byte[] data = buffer.array();
			String msg = new String(data).trim();
			System.out.println("服务端收到信息:" + msg);

			// 回写数据, 将消息回送给客户端
			ByteBuffer outBuffer = ByteBuffer.wrap("好的".getBytes());
			channel.write(outBuffer);
		} else {
			System.out.println("客户端关闭");
			key.cancel();
		}
	}


	/**
	 * 启动服务端测试
	 */
	public static void main(String[] args) throws IOException {
		NIOServer server = new NIOServer();
		server.initServer(8000);
		server.listen();
	}
}

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client {

	//需要一个Selector 
	public static void main(String[] args) {
		
		//创建连接的地址
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
		//声明连接通道
		SocketChannel sc = null;
		//建立缓冲区
		ByteBuffer buf = ByteBuffer.allocate(1024);
		
		try {
			//打开通道
			sc = SocketChannel.open();
			//进行连接
			sc.connect(address);
			
			while(true){
				//定义一个字节数组,然后使用系统录入功能:
				byte[] bytes = new byte[1024];
				System.in.read(bytes);
				
				//把数据放到缓冲区中
				buf.put(bytes);
				//对缓冲区进行复位
				buf.flip();
				//写出数据
				sc.write(buf);
				//清空缓冲区数据
				buf.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(sc != null){
				try {
					sc.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	
	}	
}

3 对应关系


ServerSocketChannel-ServerSocket

SocketChannel-Socket
Selector和SelectionKey无对应


4 代码分析


通道管理器Selector,相当于超级服务生,把门口迎接客人,服务客人的活一个人全都做了。理论上一个selector可以对应N个客户端。即监听注册事件,又处理业务。



selector.select()是阻塞的,为什么说NIO是非阻塞的?阻塞和非阻塞核心区别是面向流和面向缓冲区的区别,而且selector可设置为不阻塞:

selector.select(100)设置阻塞时间。selector.wakeup()唤醒selector。某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用selector.wakeup()方法即可。阻塞在select()方法上的线程会立马返回。若有其它线程调用了wakeup()方法,但当前没有线程阻塞在select()方法上,下个调用select()方法的线程会立即醒来。



5 selector模式

当IO事件(管道)注册到selector选择器上后,selector会为每一个管道分配一个key值,相当于标签。selector以轮询的方式进行查找注册的IO事件(管道)。当IO事件(管道)准备就绪后,selector就会识别并通过key来查找相应的管道,进行数据处理(从管道中读出或者写入数据,写到缓冲区中)。

SelectionKey.OP_ACCEPT(16):服务端接收客户端连接事件
SelectionKey.OP_CONNECT(8):客户端连接服务端事件
SelectionKey.OP_READ(1):读事件
SelectionKey.OP_WRITE(4):写事件

从理论上说一个selector可以负责任意多个Channel通道,因为JDK使用epoll替代传统的select实现,获得连接句柄没有限制。



发布了535 篇原创文章 · 获赞 1162 · 访问量 450万+

猜你喜欢

转载自blog.csdn.net/woshixuye/article/details/53729700