传统的BIO(blocking I/O)是阻塞的,服务器端:ServerSocket负责绑定IP地址,启动监听端口,然后一直等待着客户端连接,是阻塞的状态;客户端:Socket负责发起连接操作。连接成功后,读和写的操作同样是等待阻塞的。经典模型是来一个客户端,起一个线程,因为主线程要负责监听,要重起一条线程处理客户端请求。
NIO (non-blocking I/O)是同步非阻塞。打个比方,客户端请求服务器端建立连接,就好像服务器端有很多个插孔,等着客户端来插。NIO有一个大管家selecter一直在轮询处理客户端的连接和读写请求,先在那些插孔上放(register)一些key(对应编程api里SelectionKey.OP_ACCEPT),看看有没有人来连接,如果有则连接。连接之后再连接的通道上放上读写的key(下面的程序是SelectionKey.OP_READ)
package com.java.yan;
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 NioSocketDemo {
private Selector selector;
public void initServer(int port) throws IOException{
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(port));
this.selector = Selector.open();
serverChannel.register(selector,SelectionKey.OP_ACCEPT);
System.out.println("服务器已启动。。。");
}
public void listenSelector() throws IOException{
while(true){
this.selector.select();
Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next();
it.remove();
handler(key);
}
}
}
private void handler(SelectionKey key) throws IOException {
if(key.isAcceptable()){
ServerSocketChannel serverchannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverchannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()){
SocketChannel socketChannel = (SocketChannel)key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int readData = socketChannel.read(buffer);
if(readData > 0){
String info = new String(buffer.array(),"GBK").trim();
System.out.println("服务端收到数据:"+info);
}else{
System.out.println("客户端关闭。。。。");
key.cancel();
}
}
}
public static void main(String[] args) throws IOException {
NioSocketDemo niodemo = new NioSocketDemo();
niodemo.initServer(8888);
niodemo.listenSelector();
}
}
上面的是单线程模式的NIO,还有升级版的,一个selector负责轮询,但是只处理客户端连接,连接成功会有对应线程处理读写工作,引入线程池。
AIO(Asynchronous I/O) 是异步非阻塞,先前是selector主动轮询,现在换成客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理。
等待完善。。。。。。。