当前位置: 首页 > news >正文

面试官:BIO、NIO 和 AIO 有什么区别?

BIO(Blocking I/O)、NIO(Non-blocking I/O)和AIO(Asynchronous I/O)是Java中用于处理I/O操作的三种不同的编程模型.

BIO适用于连接数较少的情况,NIO适用于连接数较多但连接活跃度不高的情况,而AIO适用于连接数较多且连接活跃度较高的情况。选择合适的I/O模型取决于具体的应用场景和性能要求。

以下是他们的各自介绍以及代码示例

  1. BIO(Blocking I/O)
    • 同步阻塞I/O模型,传统的I/O模型。
    • 每个I/O操作都会阻塞当前线程,直到数据读取完成或写入完成。
    • 适用于连接数较少且固定的场景,简单易用。

代码示例:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class BIOServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(8888);System.out.println("BIO Server started on port 8888");while (true) {Socket socket = serverSocket.accept();System.out.println("Accepted connection from " + socket);BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));String message = reader.readLine();System.out.println("Received message: " + message);writer.write("Hello, client!\n");writer.flush();socket.close();}}
}
  1. NIO(Non-blocking I/O)
    • 同步非阻塞I/O模型,提供了Channel和Buffer的概念。
    • 可以使用单线程处理多个连接,提高了I/O的效率。
    • 可以实现多路复用(Selector)来处理多个通道的I/O操作。

代码示例:

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 NIOServer {public static void main(String[] args) throws IOException {ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.bind(new InetSocketAddress(8888));serverSocketChannel.configureBlocking(false);Selector selector = Selector.open();serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);System.out.println("NIO Server started on port 8888");while (true) {selector.select();Set<SelectionKey> selectedKeys = selector.selectedKeys();Iterator<SelectionKey> keyIterator = selectedKeys.iterator();while (keyIterator.hasNext()) {SelectionKey key = keyIterator.next();if (key.isAcceptable()) {ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();SocketChannel socketChannel = serverChannel.accept();socketChannel.configureBlocking(false);socketChannel.register(selector, SelectionKey.OP_READ);System.out.println("Accepted connection from " + socketChannel);} else if (key.isReadable()) {SocketChannel socketChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);socketChannel.read(buffer);buffer.flip();String message = new String(buffer.array()).trim();System.out.println("Received message: " + message);socketChannel.register(selector, SelectionKey.OP_WRITE);} else if (key.isWritable()) {SocketChannel socketChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.wrap("Hello, client!\n".getBytes());socketChannel.write(buffer);socketChannel.close();System.out.println("Message sent to client");}keyIterator.remove();}}}
}
  1. AIO(Asynchronous I/O)
    • 异步非阻塞I/O模型,提供了异步的I/O操作方式。
    • 使用异步通道(AsynchronousChannel)来处理I/O操作,可以在完成之前继续做其他事情。
    • 适用于连接数较多且连接活跃度较高的场景,如聊天服务器、网络爬虫等。

代码示例:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;public class AIOServer {public static void main(String[] args) throws IOException, InterruptedException {AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();serverChannel.bind(new InetSocketAddress(8888));System.out.println("AIO Server started on port 8888");serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {serverChannel.accept(null, this);ByteBuffer buffer = ByteBuffer.allocate(1024);socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {public void completed(Integer result, ByteBuffer buffer) {buffer.flip();String message = new String(buffer.array()).trim();System.out.println("Received message: " + message);ByteBuffer responseBuffer = ByteBuffer.wrap("Hello, client!\n".getBytes());socketChannel.write(responseBuffer, responseBuffer, new CompletionHandler<Integer, ByteBuffer>() {public void completed(Integer result, ByteBuffer buffer) {try {socketChannel.close();} catch (IOException e) {e.printStackTrace();}System.out.println("Message sent to client");}public void failed(Throwable exc, ByteBuffer buffer) {exc.printStackTrace();}});}public void failed(Throwable exc, ByteBuffer buffer) {exc.printStackTrace();}});}public void failed(Throwable exc, Void attachment) {exc.printStackTrace();}});Thread.sleep(Integer.MAX_VALUE);}
}

这些示例演示了如何使用Java的BIO、NIO和AIO来实现简单的Socket通信。 BIO使用阻塞I/O模型,NIO使用非阻塞I/O模型,AIO使用异步I/O模型。

http://www.lryc.cn/news/346151.html

相关文章:

  • HTML:元素属性详解及代码示例
  • 【Flask 系统教程 5】视图进阶
  • 代码训练LeetCode(17)存在重复元素
  • 运营模型—归因分析(Attribution Analysis)
  • 我必须要吹一波MATLAB 2024a,太牛逼了!|福利:附安装教程及下载地址
  • XMLHttpRequest与Axios详解
  • 【区块链】智能合约简介
  • 上海市计算机学会竞赛平台2024年1月月赛丙组成绩等第
  • 【算法入门教育赛2】C.曼哈顿种类 C++题解与代码
  • Electron使用 SQLite
  • 怎样的跨网软件,可以实现网间数据的安全收发?
  • Sora惊艳亮相:AI技术掀起创作革命,影视产业迎来新风貌!
  • Mac电脑安装打开APP显示问题已损坏 问题解决
  • AI 数据观 | TapData Cloud + MongoDB Atlas:大模型与 RAG 技术有机结合,落地实时工单处理智能化解决方案
  • Vulnhub靶机随笔-Hacksudo_Aliens
  • 抖店选品都怎么选品?什么样的产品更吸引人,更具有购买力?
  • 将来会是Python、Java、Golang三足鼎立吗?
  • Java入门基础学习笔记16——运算符
  • golang中三种线程安全的MAP
  • C++笔试强训day16
  • spsr 的恢复出错,导致 thumb 指令集的 it 条件运行指令运行异常,清晰的调试思路帮助快速解决问题
  • mysql binlog 如何区分db
  • ESP32 IDF linux下开发环境搭建
  • 光伏电站智能管理平台功能全面介绍
  • SSL证书 购买流程
  • C++|二叉搜索树
  • 网页html版面分析-- BeauifulSoup(python 文档解析提取)
  • 第五十八节 Java设计模式 - 适配器模式
  • 程序员的归宿。。
  • ROS服务器通信