在非阻塞模式下,单个线程一直运行,一直占用CPU资源
通过创建selector,管理多个 channel
public static void main(String[] args) throws IOException {
//1.创建 selector,管理多个 channel
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
//2.绑定事件===》建立 selector 和 channel 的关系
//SelectionKey 就是将来事件发生后,通过它可以知道事件和哪个 channel 的事件
SelectionKey sscKey = ssc.register(selector, 0, null);
//sscKey 只关注 accept 事件
sscKey.interestOps(SelectionKey.OP_ACCEPT);
ssc.bind(new InetSocketAddress(8080));
while (true){
//3.监听事件===》select 方法: 没有事件发生,线程阻塞;有事件,线程才会恢复运行
selector.select();
//4.处理事件,selectedKeys() 内部包含了所有的发生的事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
//处理 key 时,要从 selectedKeys 集合中删除,否则下次处理就会有问题
iterator.remove();
//5.区分事件类型
if (key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel sc = channel.accept();
sc.configureBlocking(false);
SelectionKey scKey = sc.register(selector, 0, null);
scKey.interestOps(SelectionKey.OP_READ);//切换为READ类型,在下次循环中,读取客户端的数据
}else if (key.isReadable()) {
try {
//拿到多个事件的channel
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
int read = channel.read(buffer); //正常断开,read = -1
if (read == -1){
key.cancel(); //客户端正常断开,将 key 从 selector 的 keys 集合中删除
}else {
buffer.flip();
}
} catch (IOException e) {
e.printStackTrace();
key.cancel(); //客户端异常断开,将 key 从 selector 的 keys 集合中删除
}
}
}
}
}