NIO: 同步非阻塞 IO
NIO 中采用 Reactor 设计模式, 注册的汇集点为 Selector,NIO 有三个主要组成部分: Channel(通道),Buffer(缓冲区),Selector(选择器)
Reactor 设计模式: Reactor 模式是一种被动事件处理模式, 即当某个特定事件发生时触发事件, 可参考,,https://www.cnblogs.com/bitkevin/p/5724410.html
NIO 采用了轮询的方式来观察事件是否执行完毕, 如: A 让 B 打印某个文件, BIO 会一直等待着 B 返回, 期间自己不做其他事情, 而 NIO 则会不断的询问 B 是否完成, 未完成则处理自己的时, 直至 B 完成
Channel(通道):Channel 是一个对象, 可以通过它读取和写入数据
Selector(对象选择器): Selector 是一个对象, 它可以注册到很多个 Channel 上, 监听各个 Channel 上发生的事件, 并且能够根据事件情况决定 Channel 读写
代码实现:(此实现参考网络上可用的例子)
NIO 客户端实现:
- package com.learn.nio.client;
- import com.study.info.HostInfo;
- import com.study.util.InputUtil;
- import java.NET.InetSocketAddress;
- import java.nio.ByteBuffer;
- import java.nio.channels.SocketChannel;
- public class NIOEchoClient {
- public static void main(String[] args) throws Exception{
- SocketChannel clientChannel = SocketChannel.open();
- clientChannel.connect(new InetSocketAddress(HostInfo.HOST_NAME,HostInfo.PORT));
- ByteBuffer buffer = ByteBuffer.allocate(50);
- boolean flag = true;
- while (flag){
- buffer.clear();
- String input = InputUtil.getString("请输入待发送的信息:").trim();
- buffer.put(input.getBytes()); // 将数据存入缓冲区
- buffer.flip(); // 重置缓冲区
- clientChannel.write(buffer); // 发送数据
- buffer.clear();
- int read = clientChannel.read(buffer);
- buffer.flip();
- System.err.print(new String(buffer.array(), 0, read));
- if("byebye".equalsIgnoreCase(input)){
- flag = false;
- }
- }
- clientChannel.close();
- }
- }
NIO 服务端实现:
- package com.learn.nio.server;
- import com.study.info.HostInfo;
- 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;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class NIOEchoServer {
- private static class EchoClientHandle implements Runnable {
- // 客户端
- private SocketChannel clientChannel;
- // 循环结束标记
- private boolean flag = true;
- public EchoClientHandle(SocketChannel clientChannel){
- this.clientChannel = clientChannel;
- }
- @Override
- public void run() {
- ByteBuffer byteBuffer = ByteBuffer.allocate(50);
- try {
- while (this.flag){
- byteBuffer.clear();
- int read = this.clientChannel.read(byteBuffer);
- String msg = new String(byteBuffer.array(), 0, read).trim();
- String outMsg = "[Echo]" + msg + "\n"; // 回应信息
- if("byebve".equals(msg)){
- outMsg = "会话结束, 下次再见!";
- this.flag = false;
- }
- byteBuffer.clear();
- byteBuffer.put(outMsg.getBytes()); // 回传信息放入缓冲区
- byteBuffer.flip();
- this.clientChannel.write(byteBuffer);// 回传信息
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws Exception{
- // 为了性能问题及响应时间, 设置固定大小的线程池
- ExecutorService executorService = Executors.newFixedThreadPool(10);
- // NIO 基于 Channel 控制, 所以有 Selector 管理所有的 Channel
- ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
- // 设置为非阻塞模式
- serverSocketChannel.configureBlocking(false);
- // 设置监听端口
- serverSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
- // 设置 Selector 管理所有 Channel
- Selector selector = Selector.open();
- // 注册并设置连接时处理
- serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
- System.out.println("服务启动成功, 监听端口为:" + HostInfo.PORT);
- // NIO 使用轮询, 当有请求连接时, 则启动一个线程
- int keySelect = 0;
- while ((keySelect = selector.select())> 0){
- Set<SelectionKey> selectionKeys = selector.selectedKeys();
- Iterator<SelectionKey> iterator = selectionKeys.iterator();
- while (iterator.hasNext()){
- SelectionKey next = iterator.next();
- if(next.isAcceptable()){ // 如果是连接的
- SocketChannel accept = serverSocketChannel.accept();
- if(accept != null){
- executorService.submit(new EchoClientHandle(accept));
- }
- iterator.remove();
- }
- }
- }
- executorService.shutdown();
- serverSocketChannel.close();
- }
- }
工具类:
- package com.study.util;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class InputUtil {
- private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));
- private InputUtil(){
- }
- public static String getString(String prompt){
- boolean flag = true; // 数据接受标记
- String str = null;
- while (flag){
- System.out.println(prompt);
- try {
- str = KEYBOARD_INPUT.readLine(); // 读取一行数据
- if(str == null || "".equals(str)){
- System.out.println("数据输入错误, 不允许为空!");
- }else {
- flag = false;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return str;
- }
- }
- package com.study.info;
- public calss HostInfo {
- public static final String HOST_NAME = "localhost";
- public static final int PORT = 9999;
- }
NIO 结构参考文章: https://www.cnblogs.com/sxkgeek/p/9488703.html#_label2
来源: https://www.cnblogs.com/shlearn/p/11689427.html