当前位置:网站首页>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
边栏推荐
- C # use log4net plug-in to output logs to files
- buuReserve(4)
- Queue assistant | product update log in June 2022
- Download, installation and development environment construction of "harmonyos" deveco
- AcWing-每日一题
- Docker modifying the MySQL configuration file attached to the host does not take effect?
- Huffman coding principle
- XSS labs (1-10) break through details
- On stock price prediction model (3): are you falling into the trap of machine learning
- 文件服务器FastDFS
猜你喜欢

【硬十宝典】——7.1【动态RAM】DDR硬件设计要点

浅谈eval与assert一句话木马执行区别
![[database] CTE (common table expression)](/img/36/812026995f5d0b64d26f1667638010.png)
[database] CTE (common table expression)

Download, installation and development environment construction of "harmonyos" deveco

UIToolkit工具模板工程

哈夫曼编码原理

Quick sort

Merge_sort

How does the national standard gb28181 protocol easygbs platform realize device video recording and set streaming IP?

微信小程序 - 从入门到入土
随机推荐
UIToolkit工具模板工程
Press in and pop-up sequence of "Niuke | daily question" stack
Curve curvature display
【Star项目】小帽飞机大战(三)
vulnhub Lampião: 1
如何删除语句审计日志?
Celery takes up large memory - memory leak
[today in history] July 18: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal
docker修改挂载到宿主机上的mysql配置文件不生效?
< II> ObjectARX development: create and edit basic graphic objects
Fastdfs supports dual IP and IPv6
文件服务器FastDFS
浅谈eval与assert一句话木马执行区别
AcWing-每日一题
【硬十宝典】——7.2【动态RAM】DDR4与DDR3区别解析
Ruby on rails Code Execution Vulnerability (cve-2020-8163) technical analysis, research, judgment and protection
MySQL table write lock
Kubernetes scheduling concept and workflow
MySQL optimized index and index invalidation
20220725 自动控制原理中的卷积Convolution