1、目的:了解NIO服务的工作原理
2、代码:
代码语言:javascript复制/**
* @Author: Liu
* @Descripition:NIO测试
* @Date; Create in 2020/3/14 16:10
**/
public class NIOServerDemo {
private int port = 8080;
private Selector selector;
private ByteBuffer buffer = ByteBuffer.allocate(1024);
//初始化完毕
public NIOServerDemo(int port) {
this.port = port;
try {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(this.port));
//设置非阻塞
server.configureBlocking(false);
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listen() {
System.out.println("listen on " this.port ".");
try {
while (true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
//数据就绪,数据可读,可写等 看key的方法
process(key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//具体办理业务的方法,处理业务逻辑
//每次轮询调用一次,同步
private void process(SelectionKey key) throws IOException {
//针对每一种状态有一个反应
if (key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
//体现非阻塞,返回一个状态和反馈
SocketChannel accept = channel.accept();
channel.configureBlocking(false);
key = channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
int read = channel.read(buffer);
if (read > 0) {
buffer.flip();
String content = new String(buffer.array(), 0, read);
SelectionKey register = channel.register(selector, SelectionKey.OP_READ);
register.attach(content);
System.out.println("读取内容:" content);
}
} else if (key.isWritable()) {
SocketChannel channel = (SocketChannel) key.channel();
String content = (String) key.attachment();
channel.write(ByteBuffer.wrap(("输出:" content).getBytes()));
channel.close();
}
}
public static void main(String[] args) {
new NIOServerDemo(8080).listen();
}
}
每天提高一点点