当前位置:网站首页>NiO example
NiO example
2022-07-28 06:44:00 【yfyh2021】
NIO(Non Blocking IO)
Synchronous nonblocking , The server implementation mode is that one thread can handle multiple requests ( Connect ), All connection requests sent by the client are registered with the multiplexer selector On , The multiplexer polls the connection to have IO The request is processed ,JDK1.4 Start introducing .
Compared with tradition BIO The most intuitive understanding is not to block , Let's just make it simple NIO Take a look at
package com.tuling.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NioServer {
// Save the client connection
static List<SocketChannel> channelList = new ArrayList<>();
public static void main(String[] args) throws IOException {
// establish NIO ServerSocketChannel, And BIO Of serverSocket similar
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(9000));
// Set up ServerSocketChannel Non blocking
serverSocket.configureBlocking(false);
System.out.println(" Service started successfully ");
while (true) {
// Non-blocking mode accept Method will not block , Otherwise, it will block
// NIO The non blocking of is implemented internally by the operating system , The underlying call linux Kernel accept function
SocketChannel socketChannel = serverSocket.accept();
if (socketChannel != null) { // If there is a client connecting
System.out.println(" Successful connection ");
// Set up SocketChannel Non blocking
socketChannel.configureBlocking(false);
// Save the client connection in List in
channelList.add(socketChannel);
}
// Traverse the connection to read data
Iterator<SocketChannel> iterator = channelList.iterator();
while (iterator.hasNext()) {
SocketChannel sc = iterator.next();
ByteBuffer byteBuffer = ByteBuffer.allocate(128);
// Non-blocking mode read Method will not block , Otherwise, it will block
int len = sc.read(byteBuffer);
// If there's data , Print out the data
if (len > 0) {
System.out.println(" Message received :" + new String(byteBuffer.array()));
} else if (len == -1) { // If the client is disconnected , hold socket Remove... From the set
iterator.remove();
System.out.println(" Client disconnected ");
}
}
}
}
}Open two telnet Try to link

It is found that both network connections are successfully linked , And not to BIO Also blocked in accept method .
But there is a big problem with this simple method , We are traversal chanel, If most links are not sent , But the link is not broken , We have a lot of useless links to traverse .
Here leads us NIO Multiplexer of .
Selector( multiplexer ):channel Will register to selector in ,selector Will listen channel Events in , Its essence is to call linux In the server Epoll function
Code up
package com.tuling.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioSelectorServer {
public static void main(String[] args) throws IOException {
// establish NIO ServerSocketChannel
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(9000));
// Set up ServerSocketChannel Non blocking
serverSocket.configureBlocking(false);
// open Selector Handle Channel, creating epoll
Selector selector = Selector.open();
// hold ServerSocketChannel Sign up to selector On , also selector Client side accept Connection operations are of interest
SelectionKey selectionKey = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
System.out.println(" Service started successfully ");
while (true) {
// Blocking waits for events to be processed to occur
selector.select();
// obtain selector Of all events registered in SelectionKey example
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
// Traverse SelectionKey Deal with the incident
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// If it is OP_ACCEPT event , Then get the connection and register the event
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = server.accept();
socketChannel.configureBlocking(false);
// Only read events are registered here , If you need to send data to the client, you can register write events
SelectionKey selKey = socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(" Client connection successful ");
} else if (key.isReadable()) { // If it is OP_READ event , Read and print
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(128);
int len = socketChannel.read(byteBuffer);
// If there's data , Print out the data
if (len > 0) {
System.out.println(" Message received :" + new String(byteBuffer.array()));
} else if (len == -1) { // If the client disconnects , close Socket
System.out.println(" Client disconnected ");
socketChannel.close();
}
}
// Delete this processed... From the event set key, Prevent next time select Reprocessing
iterator.remove();
}
}
}
}
边栏推荐
猜你喜欢

mysql-8.0.17-winx64(附加navicat)手动配置版安装

valgrind工具

What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation

中国剩余定理 个人理解

AQS之semaphore源码分析
![[pta---- output full arrangement]](/img/66/d1699cd55fa5ff4a55e3e150d02c1b.png)
[pta---- output full arrangement]

redis缓存设计与性能优化
![[队列,栈的简单应用----包装机]](/img/bc/617b1eb35558c4f948018f593a1de5.jpg)
[队列,栈的简单应用----包装机]
![[dynamic planning -- the best period series for buying and selling stocks]](/img/90/9060eabc9b9e7f660504806fde282d.png)
[dynamic planning -- the best period series for buying and selling stocks]

Leetcode brush question diary sword finger offer II 048. serialization and deserialization binary tree
随机推荐
费马小定理
OJ 1131 美丽数
What are the open earphones? Four types of air conduction earphones with excellent sound quality are recommended
OJ 1045 reverse and add
数组解法秘籍
[dynamic planning -- the best period series for buying and selling stocks]
About the collation of shader keyword
【C笔记】数据类型及存储
江中ACM新生10月26日习题题解
图形管线基础(一)
Development of clip arbitrage / brick carrying arbitrage system
What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation
Two dimensional array practice: spiral matrix
ZOJ Problem 1005 jugs
Dynamic planning -- multi-step stair climbing (advanced version of stair climbing)
Icc2 (IV) routing and postroute optimization
Pyppeter drop-down selenium drop-down
Everything you don't know about time complexity is here
[PTA--利用队列解决猴子选大王问题】
2021-11-10