当前位置:网站首页>NIO's Selector execution process
NIO's Selector execution process
2022-08-02 21:04:00 【i attack siege lion】
一、Seletor是什么?
selector 单从字面意思不好理解,Seletor是一个监听器,它可以监听Channel中发生的事件.Channelcan be registered atSeletor中,when these are registeredChannel在事件发生时,Seletor的select 方法就会返回这些事件交给 thread 来处理.
二、Seletordifference from multithreading
It is not easy to understand just from the above explanation,需要结合服务器的设计演化来理解它的用途
多线程版设计
to clients in the networksocket请求,If each request opens a thread to handle,Then the system memory usage is high,Thread context switching costs are also high,The stress on the system can be very high.
线程池版设计
使用线程池,Optimized thread creation,But in blocking mode,线程仅能处理一个 socket 连接, 仅适合短连接场景
selector版本
selector 的作用就是配合一个线程来管理多个 channel,获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,不会让线程吊死在一个 channel 上.适合连接数特别多,但流量低的场景(low traffic)

三、selector单线程处理多socket案例
服务端代码:
@Slf4j
public class ChannelDemo6 {
public static void main(String[] args) {
try (ServerSocketChannel channel = ServerSocketChannel.open()) {
channel.bind(new InetSocketAddress(8080));
System.out.println(channel);
Selector selector = Selector.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int count = selector.select();
log.debug("select count: {}", count);
// 获取所有事件
Set<SelectionKey> keys = selector.selectedKeys();
// 遍历所有事件,逐一处理
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
// 判断事件类型
if (key.isAcceptable()) {
ServerSocketChannel c = (ServerSocketChannel) key.channel();
// 必须处理
SocketChannel sc = c.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
log.debug("连接已建立: {}", sc);
}
else if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(128);
int read = sc.read(buffer);
if(read == -1) {
key.cancel();
sc.close();
} else {
buffer.flip();
debugAll(buffer);
}
}
// 处理完毕,必须将事件移除
iter.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码:
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080)) {
System.out.println(socket);
socket.getOutputStream().write("world".getBytes());
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法解释:
- ServerSocketChannelused to create the serverChannel,它有点像ServerSocket.
- channel.configureBlocking(false);设置channel为非阻塞,这样如果accpet的时候,如果没有连接,就会返回null.
- channel.register(selector, SelectionKey.OP_ACCEPT)将channel注册到selector中,监听accept连接事件
- selector.select(),会阻塞,等待客户端连接
- selector.selectedKeys(),event production,will add events to this collection
四、selector事件
- accept Fired when a connection is made
- connect Fired when a client establishes a connection
- read Raises a readable event when a client message is received
- 可写事件
边栏推荐
- NeRF: The Secret of 3D Reconstruction Technology in the Popular Scientific Research Circle
- redis总结_多级缓存
- 如何减轻企业账户被劫持的攻击?
- 无法超越的100米_百兆以太网传输距离_网线有哪几种?
- 载20(S)-人参皂苷/细胞穿膜肽-单克隆抗体-载丝裂霉素白蛋白纳米微球的制备
- selenium安装和环境配置Firefox
- 指针常量和常量指针概述
- 来亲自手搭一个ResNet18网络
- 常用随机变量的数学期望和方差
- LiveGBS国标GB/T28181流媒体平台支持主子码流切换主码流stream/streamprofile
猜你喜欢

leetcode:622. 设计循环队列【循环队列板子】

天翼云4.0来了!千城万池,无所不至!

宝塔搭建实测-基于ThinkPHP5.1的wms进销存源码

codeforces:E. Add Modulo 10【状态压缩 + 找规律】

Data Governance: The Evolution of Data Integration and Application Patterns

一文看懂推荐系统:概要01:推荐系统的基本概念

如何确保智能工厂的安全?

55.【sort函数的升序降序】

Monitor is easy to Mars debut: distributed operations help TOP3000 across management gap

技术人生 | 如何设定业务目标
随机推荐
「日志」深度学习 CUDA环境配置
有关代购系统搭建的那点事
什么是会话劫持以及如何阻止它
共享平台如何提高财务的分账记账效率?
来亲自手搭一个ResNet18网络
解决多版本jar包冲突问题
VSTO踩坑记录(1)- 从零开始开发outlook插件
C# 术语
多聚体/壳聚糖修饰白蛋白纳米球/mPEG-HSA聚乙二醇人血清白蛋白纳米球的制备与研究
ROS基本编程概述
LeetCode 2333. 最小差值平方和(贪心)
Taking advantage of cloud-network integration, e-Surfing Cloud has paved the way for digital transformation for government and enterprises
织梦提示信息提示框美化
IDEA相关配置(特别完整)看完此篇就将所有的IDEA的相关配置都配置好了、设置鼠标滚轮修改字体大小、设置鼠标悬浮提示、设置主题、设置窗体及菜单的字体及字体大小、设置编辑区主题、通过插件更换主题
golang刷leetcode动态规划(10)编辑距离
如何减轻企业账户被劫持的攻击?
记一次 .NET 某工控自动化控制系统 卡死分析
How can services start smoothly under tens of millions of QPS
Go 语言快速入门指南: 介绍及安装
54.【system系统互动函数大总结】