本文介绍了 3种 java io模型,包括 BIO,NIO, AIO;
| IO模型名称 | 描述 | 工作原理 |
| BIO-Blocking IO | 同步并阻塞式IO | 一个服务器线程处理一个客户端连接 |
| NIO-Non-blocking IO | 同步非阻塞式IO | 一个服务器线程处理多个客户端连接,使用io多路复用(选择器); |
| AIO-Asynchronous IO | 异步非阻塞式IO |
|
1)服务端:
- /**
- * @Description 阻塞式IO服务器
- * @author xiao tang
- * @version 1.0.0
- * @createTime 2022年08月13日
- */
- public class BIOServer {
- public static void main(String[] args) throws IOException {
- // 创建一个线程池
- ExecutorService threadPool = Executors.newCachedThreadPool();
- int order = 0;
-
- // 创建 服务器 套接字
- ServerSocket serverSocket = new ServerSocket(6666);
- System.out.println("服务器启动成功.");
- while(true) {
- System.out.println("等待客户端请求");
- Socket socket = serverSocket.accept(); // 没有客户端请求,accept阻塞
- System.out.printf("客户端[%d]请求建立连接\n", ++order);
- final int orderCopy = order;
- threadPool.execute(()->{
- handler(socket, orderCopy);
- });
- }
- }
-
- /**
- * @description 与客户端通讯
- * @param socket 连接套接字
- * @author xiao tang
- * @date 2022/8/13
- */
- public static void handler(Socket socket, int order) {
- byte[] byteArr = new byte[1024];
-
- try {
- // 读取客户端发送的数据
- InputStream inputStream = socket.getInputStream();
- int length = 0;
- // 客户端没有数据,read阻塞
- // while( ( length = inputStream.read(byteArr))!= -1) {
- // System.out.println(new String(byteArr, 0, length));
- // }
- while(true) {
- System.out.printf("线程id[%s],等待客户端[%d]发送数据\n", Thread.currentThread().getId(), order);
- length = inputStream.read(byteArr);
- if (length == -1) break;
- System.out.printf("线程id[%s],客户端[%d]:" + new String(byteArr, 0, length) + "\n", Thread.currentThread().getId(), order);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭与客户端的连接
- try {
- socket.close();
- System.out.printf("关闭与客户端[%d]的连接\n", order);
- } catch (IOException e) {
- }
- }
- }
- }
2)客户端 :采用 win10的命令行 telnet 进程;
发送过程如下:
