public void selector() throws IOException {
//先给缓冲区申请内存空间
ByteBuffer buffer = ByteBuffer.allocate(1024);
//打开Selector为了它可以轮询每个 Channel 的状态
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);//设置为非阻塞方式
ssc.socket().bind(new InetSocketAddress(8080));
ssc.register(selector, SelectionKey.OP_ACCEPT);//注册监听的事件
while (true) {
Set selectedKeys = selector.selectedKeys();//取得所有key集合
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
SocketChannel sc = ssChannel.accept();//接受到服务端的请求
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
it.remove();
} else if
((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
SocketChannel sc = (SocketChannel) key.channel();
while (true) {
buffer.clear();
int n = sc.read(buffer);//读取数据
if (n <= 0) {
break;
}
buffer.flip();
}
it.remove();
}
}
}
}
END 题外推荐 十期推荐 【291期】你了解Log4j2中RollingFile的文件滚动更新机制吗? 【292期】Linux面试最高频的5个基本问题 【293期】面试官:你知道写时复制(Copy-On-Write)在Java中是如何被应用的吗? 【294期】面试官:谈谈你对缓存的使用和理解 【295期】面试官:已经用k8s来部署运维各个微服务的组件,是否可以不用整套微服务? 【296期】面试官:详细说说对MQ消息队列的理解以及主流MQ的优缺点 【297期】面试官:为什么在new 对象里面使用自动注入对象会报空指针异常? 【298期】面试官:如何保证token的安全 【299期】面试官:详细说一说MySQL InnoDB 中意向锁的作用 【300期】面试官:Elasticsearch 是如何做到快速检索的 ? ~