JDK包装了统一的API;
实际上底层就是调用了 Linux的 select、poll、epoll 接口。
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
serverSocketChannel.configureBlocking(false);
Selector selector=Selector.open();
SelectionKey selectionKey=serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
for(SelectionKey key : selectionKeys){
if(key.isAcceptable()){
System.out.println("accept socket.");
ServerSocketChannel s= (ServerSocketChannel) key.channel();
SocketChannel socketChannel=s.accept();
if(socketChannel!=null) {
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
selectionKeys.remove(key);
}else if(key.isReadable()){
SocketChannel socketChannel= (SocketChannel) key.channel();
ByteBuffer byteBuffer= ByteBuffer.allocate(1024);
byteBuffer.clear();
socketChannel.read(byteBuffer);
byteBuffer.flip();
System.out.println("receive data : "+ new String(byteBuffer.array(),"utf-8"));
selectionKeys.remove(key);
}
}
}
底层原理参考之前的一篇文章:
https://www.jianshu.com/p/fb88b1504ceb