传统BIO同步阻塞:
阻塞节点1:等待客户端的连接
阻塞节点2:客户端连接请求进来后,需要创建独立的线程处理,且当前线程暂时没有数据可读,则线程就阻塞在 Read 操作上
NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据先总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道 。
Selector 、 Channel 和 Buffer 的关系:
- 一个Selector实例对应一个线程,
- 一个Selector可以注册多个channel 实例,每个channel都有唯一一个与之对应的Buffer实例
- Selector 会根据不同的事件,在各个channel上切换【事件决定】
- Buffer 就是一个内存块 , 底层是有一个数组。数据读和写都必须通过Buffer【连接点其实是Channle,而读写的容器是Buffer。】
- channel中数据的读取写入是双向的【flip 方法切换】, 可以返回底层操作系统的情况, 比如Linux , 底层的操作系统通道就是双向的
NIO的三个主要特点:面向缓冲、同步非阻塞和多路复用。
NIO示例
//网络服务器端程序
public class NIOServer {
public static void main(String[] args) throws Exception{
//1. 得到一个ServerSocketChannel对象
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//2. 得到一个Selector对象
Selector selector=Selector.open();
//3. 绑定一个端口号, 在服务器的6666监听
//serverSocketChannel.bind(new InetSocketAddress(6666));
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
//4. 设置非阻塞方式
serverSocketChannel.configureBlocking(false);
//5. 把ServerSocketChannel对象注册给Selector对象
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//6. 干活
while(true){
//6.1 监控客户端
//如果使用 selector.select() 就会阻塞在这里的
if(selector.select(1000)==0){ //nio非阻塞式的优势
System.out.println("Server:等待了1秒,无客户端连接");
continue;
}
//6.2 得到SelectionKey,判断通道里的事件
Iterator<SelectionKey> keyIterator=selector.selectedKeys().iterator();
while(keyIterator.hasNext()){
SelectionKey key=keyIterator.next();
if(key.isAcceptable()){ //客户端连接请求事件
SocketChannel socketChannel=serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if(key.isReadable()){ //读取客户端数据事件
SocketChannel channel=(SocketChannel) key.channel();
ByteBuffer buffer=(ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("接收到客户端数据:"+new String(buffer.array()));
}
// 6.3 手动从集合中移除当前key,防止重复处理
keyIterator.remove();
}
}
}
}
//网络客户端程序
public class NIOClient {
public static void main(String[] args) throws Exception{
//1. 得到一个网络通道
SocketChannel channel=SocketChannel.open();
//2. 设置非阻塞方式
channel.configureBlocking(false);
//3. 提供服务器端的IP地址和端口号
InetSocketAddress address=new InetSocketAddress("127.0.0.1",6666);
//4. 连接服务器端
if(!channel.connect(address)){
while(!channel.finishConnect()){ //nio非阻塞式
System.out.println("客户端: 因为连接需要时间,客户端不会阻塞,可以做个计算工作...");
}
}
//连接成功了..
//5. 得到一个缓冲区并存入数据
String msg="hello,word";
ByteBuffer writeBuf = ByteBuffer.wrap(msg.getBytes());
//6. 发送数据
channel.write(writeBuf);
System.in.read();
}
}