当前位置:网站首页>NiO implementation
NiO implementation
2022-07-26 06:58:00 【Zhang Zhengdong】
Server implementation :
public static void main(String[] args) {
int port = 7236;
//NIO Multiplexing
// Creating a thread pool
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 The construction method uses Protected Embellished
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
// Binding services
serverSocketChannel.bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
/* Set up SocketChannel Is non-blocking mode After setting , You can call... In asynchronous mode connect(), read() and write() 了 */
serverSocketChannel.configureBlocking(false);
//
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();// Block waiting for ready 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(" Hello , The world -zzd"));
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Client implementation :
public static void main(String[] args) {
int port = 7236;
//Socket client ( Receive information and print )
try(Socket socket = new Socket(InetAddress.getLocalHost(), port)){
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.lines().forEach(s-> System.out.println(" client :" + s));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Explanation of calling process :
- First , adopt Selector.open() Create a Selector, As a dispatcher like role
- then , Create a ServerSocketChannel, And to the Selector register , By designation SelectionKey.OP_ACCEPT, Tell the dispatcher , It focuses on newly established connection requests
- Why should we explicitly configure non blocking mode ? This is because in blocking mode , Registration is not allowed , Will throw out IllegalBlockingModeException abnormal
- Selector Blocked in select operation , When there is Channel An access request has occurred , Will be awakened
边栏推荐
- 服装行业如何实现数字化生产模式
- Delete ^m from VIM
- LeetCode刷题1:题目分类
- 树莓派连接天猫精灵音箱通过蓝牙播放音乐的方法
- On stock price prediction model (3): are you falling into the trap of machine learning
- How to solve the crash when the easygbs platform edits the device management group?
- MySql 执行计划
- Open includeexceptiondetailinfaults on the server (from servicebehaviorattribute or from & lt; servicedebug & gt; to configure behavior) to send exception information back
- [Star Project] small hat aircraft War (III)
- MySQL intent lock
猜你喜欢

文件服务器FastDFS

字符串和内存函数

The creation of "harmonyos" project and the use of virtual machines

微信小程序 - 从入门到入土

What to pay attention to when using German chicks for the first time
![[hard ten treasures] - 7.2 [dynamic RAM] analysis of the difference between DDR4 and DDR3](/img/e0/690809c029346fbd0889c16d610145.png)
[hard ten treasures] - 7.2 [dynamic RAM] analysis of the difference between DDR4 and DDR3

你了解MySQL都包含哪些“零件“吗?

UIToolkit中显示汉字

Press in and pop-up sequence of "Niuke | daily question" stack

opengauss简易版安装报错
随机推荐
7. Reverse integer integer
源代码加密技术发展阶段
从Architecture带你认识JVM
20220724 三角函数系的正交性
What to pay attention to when using German chicks for the first time
数据库性能测试(mysql)
UIToolkit工具模板工程
二叉树知识总结
替换license是否要重启数据库?
MySql 执行计划
针对前面文章的整改思路
【Star项目】小帽飞机大战(二)
Is there any online account opening process of Huatai Securities? Is online account opening safe
『期末复习』16/32位微处理器(8086)基本寄存器
MySQL table write lock
"XXXX" is running, which may cause the system to jam, reduce the standby time, and click Close "
Manifest merger failed with multiple errors, see logs
Ruby on rails Code Execution Vulnerability (cve-2020-8163) technical analysis, research, judgment and protection
7. Reverse Integer整数反转
Press in and pop-up sequence of "Niuke | daily question" stack