IO多路复用底层主要依赖于操作系统的epoll功能,通过epoll_create,epoll_ctl,epoll_wait三个函数完成多路复用器的创建,事件注册,时间选择的过程。
下面就是基于Java nio的示例程序。
public class TestNio {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8965));
serverSocketChannel.configureBlocking(false);
//实际调用操作系统底层的epoll_create函数
Selector selector = Selector.open();
//实际调用操作系统底层的epoll_ctl函数
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer readBuff = ByteBuffer.allocate(1024);
ByteBuffer writeBuff = ByteBuffer.allocate(128);
writeBuff.put("received".getBytes());
writeBuff.flip();
//selector.select()实际是调用操作系统的epoll_wait函数,此处会阻塞
while(selector.select() > 0){