当前位置:网站首页>NIO实现
NIO实现
2022-07-26 06:54:00 【张正栋】
服务端实现:
public static void main(String[] args) {
int port = 7236;
//NIO多路复用
//创建线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, 4, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
threadPool.execute(new Runnable() {
@Override
public void run() {
try (Selector selector = Selector.open();
//ServerSocketChannel构造方法使用Protected进行修饰的
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
//绑定服务
serverSocketChannel.bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
/* 设置 SocketChannel 为非阻塞模式 设置之后,就可以在异步模式下调用connect(), read() 和write()了 */
serverSocketChannel.configureBlocking(false);
//
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();//阻塞等待就绪的Channel
//
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
try (SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();) {
channel.write(Charset.defaultCharset().encode("你好,世界-zzd"));
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
客户端实现:
public static void main(String[] args) {
int port = 7236;
//Socket客户端(接收信息并打印)
try(Socket socket = new Socket(InetAddress.getLocalHost(), port)){
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.lines().forEach(s-> System.out.println("客户端:" + s));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
调用过程讲解:
- 首先,通过Selector.open()创建一个Selector,作为类似调度员的角色
- 然后,创建一个ServerSocketChannel,并且向Selector注册,通过指定SelectionKey.OP_ACCEPT,告诉调度员,它关注的是新建立的连接请求
- 为甚我们要明确配置非阻塞模式?这是因为阻塞模式下,注册操作是不允许的,会抛出IllegalBlockingModeException异常
- Selector阻塞在select操作,当有Channel发生接入请求,就会被唤醒
边栏推荐
- Is the passenger flow always low? There is something wrong with the location of your store!
- 「“xxxx“正在运行,可能导致系统卡顿,降低待机时间,点按关闭」处理
- String and memory functions
- "Final review" 16/32-bit microprocessor (8086) basic register
- 『HarmonyOS』探索HarmonyOS应用
- Downloadutilse tool class without error
- LeetCode刷题1:题目分类
- [hardware ten treasures] - 7.1 [dynamic RAM] key points of DDR hardware design
- Vim中删除^M
- Can C use reflection to assign values to read-only attributes?
猜你喜欢
随机推荐
MySQL optimized index and index invalidation
MySQL table write lock
Rust语言- Slice(切片)类型(&[u8])
Queue assistant | product update log in June 2022
Heap sort
[hardware ten treasures] - 7.1 [dynamic RAM] key points of DDR hardware design
优炫数据库JDBC打开日志方式有哪些
『牛客|每日一题』 栈的压入、弹出序列
Binary tree knowledge summary
【无标题】转载
7. Reverse Integer整数反转
mySql建表的基本操作 与常见的函数
< II> ObjectARX development: create and edit basic graphic objects
How strong is the working ability of a project manager with a monthly salary of 50000?
针对前面文章的整改思路
排序问题:冒泡排序,选择排序,插入排序
解决 Chrome 浏览器被毒霸篡改问题
[database] CTE (common table expression)
<二> objectARX开发:创建和编辑基本图形对象
How does the seckill system ensure that the database does not crash and prevent oversold goods








