简介
NIO的全称是New I/O,与之相对应的是Java中传统的I/O,这里都指的是Java的API包。
传统的IO包提供的是同步阻塞IO,即当用户线程发出IO请求后,内核会去查看数据是否已经就绪,若未就绪,则用户线程会处于阻塞状态(让出CPU),当数据就绪后,内核会将数据复制到用户线程,并把结果返回给用户线程,同时接触用户线程的阻塞,同步体现在用户线程需要等待数据就绪后才能向后执行(后面的执行依赖于前面的结果)。服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,线程数量也会受到。
而NIO包提供的IO是同步非阻塞IO,非阻塞体现在处理线程发起IO请求后,会直接得到返回结果,即便在数据未就绪的情况下,也能马上得到失败信息。而同步体现在处理线线程需要主动去轮询直到发现数据就绪,再主动将数据从内核拷贝到用户线程。服务器实现模式为多个连接一个线程(IO多路复用),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求时才启动一个线程进行处理。
SocketChannel和ServerSocketChannel
与Socket类和ServerSocket类相对应,NIO也提供了SocketChannel和ServerSocketChannel两种不同的套接字通道实现。这两种新增的通道都支持阻塞和非阻塞两种模式。
低负载、低并发的应用程序可以选择同步阻塞I/O以降低编程复杂度;对于高负载、高并发的网络应用,需要使用NIO的非阻塞模式进行开发。
缓冲区Buffer
在NIO类库中加入Buffer对象,体现了新库与原I/O的一个重要区别。
在面向流的I/O中,可以将数据直接写入或者将数据直接读到Stream对象中。
在NIO库中,所有数据都是用缓冲区处理的。在读取数据时,它是直接读到缓冲区中的;在写入数据时,写入到缓冲区中。任何时候访问NIO中的数据,都是通过缓冲区进行操作。
Selector
Selector运行单线程处理多个Channel,如果你的应用打开了多个通道,但每个连接的流量都很低,使用Selector就会很方便。
例如在一个聊天服务器中。要使用Selector,得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新的连接进来、数据接收等。
代码实例
代码会附上详细的注释,可以复制到对应的编程软件中帮助理解。
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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiplexerTimeServer implements Runnable {
private Selector selector;
private ServerSocketChannel servChannel;
private volatile boolean stop;
private ExecutorService executorService = Executors.newFixedThreadPool(10);
/**
* 初始化多路复用器、绑定监听端口
*
* @param port
*/
public MultiplexerTimeServer(int port) {
try {
//打开selector
selector = Selector.open();
//打开ServerSocketChannl
servChannel = ServerSocketChannel.open();
//设置为非阻塞模式
servChannel.configureBlocking(false);
//绑定端口号
servChannel.socket().bind(new InetSocketAddress(port), 1024);
//将Channel注册到selector
servChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("The time server is start in port : " + port);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public void stop() {
this.stop = true;
}
@Override
public void run() {
while (!stop) {
try {
//轮询是否有请求 非阻塞
while (selector.select(1000) == 0) {
System.out.println("服务端等待请求.");
}
//有请求得到SelectionKeys
Set<SelectionKey> SelectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = SelectionKeys.iterator();
SelectionKey key = null;
while (it.hasNext()) {
key = it.next();
//将selectionKey交给处理线程处理
executorService.submit(new InputHandler(key));
it.remove();
}
} catch (Throwable t) {
t.printStackTrace();
}
} // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭,所以不需要重复释放资源
if (selector != null) {
executorService.shutdown();
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class InputHandler implements Runnable {
private SelectionKey selectionKey;
public InputHandler(SelectionKey selectionKey) {
this.selectionKey = selectionKey;
}
@Override
public void run() {
try {
if (selectionKey.isValid()) { // 处理新接入的请求消息
if (selectionKey.isAcceptable()) { // 如果是连接请求
//拿到serversocketchannal
ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
//得到对应的socketChannel
SocketChannel sc = ssc.accept();
//设置为非阻塞模式
sc.configureBlocking(false);
//注册到selector交给selector管理
sc.register(selector, SelectionKey.OP_READ);
}
if (selectionKey.isReadable()) { // 如果为读
//拿到socketChannel
SocketChannel sc = (SocketChannel) selectionKey.channel(); //sc.setOption(SocketOption)
//分配buffer
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
//将channel里的数据读入到buffer
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
//告诉buffer我要读数据了
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes, "UTF-8");
System.out.println("The time server receive order : "
+ body);
String currentTime = "QUERY TIME ORDER"
.equalsIgnoreCase(body) ? new java.util.Date(
System.currentTimeMillis()).toString()
: "BAD ORDER";
//处理写入
doWrite(sc, currentTime);
} else if (readBytes < 0) { // 对端链路关闭
selectionKey.cancel();
sc.close();
} else
; // 读到0字节,忽略
}
}
} catch (IOException e) {
if (selectionKey != null) {
selectionKey.cancel();
if (selectionKey.channel() != null) {
try {
selectionKey.channel().close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
private void doWrite(SocketChannel channel, String response)
throws IOException {
if (response != null && response.trim().length() > 0) {
byte[] bytes = response.getBytes();
//分配buffer内存
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
//写入到buffer
writeBuffer.put(bytes);
//设置limit = position position为0
writeBuffer.flip();
//将buffer里的数据写入到channel里
channel.write(writeBuffer);
}
System.out.println("response : " + response);
}
}
public static void main(String[] args) throws IOException {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) { // 采用默认值
}
}
MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();
}
}
总结
(1)客户端发起的连接操作是异步的,可以通过在多路复用器注册OP_CONNECT等待后续结果,不需要像之前的客户端那样被同步阻塞。
(2)SocketChannel的读写操作都是异步的,如果没有可读写的数据它不会同步等待,直接返回,这样I/O通信线程就可以处理其他的链路,不需要同步等待这个链路可用。
(3)线程模型的优化:由于JDK的Selector在Linux等主流操作系统上通过epoll实现,它没有连接句柄数的限制(只受限于操作系统的最大句柄数或者对单个进程的句柄限制),这意味着一个Selector线程可以同时处理成千上万个客户端连接,而且性能不会随着客户端的增加而线性下降。因此,它非常适合做高性能、高负载的网络服务器。