通过Selector组件监控多个Channel事件

在非阻塞模式下,单个线程一直运行,一直占用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 集合中删除
	           }
	       }
	   }
  }
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值