自己的网站怎么做进销存百度浏览器网址大全
BIO(Blocking I/O)、NIO(Non-blocking I/O)和AIO(Asynchronous I/O)是Java中用于处理I/O操作的三种不同的编程模型.
BIO适用于连接数较少的情况,NIO适用于连接数较多但连接活跃度不高的情况,而AIO适用于连接数较多且连接活跃度较高的情况。选择合适的I/O模型取决于具体的应用场景和性能要求。
以下是他们的各自介绍以及代码示例
- 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();}}
}
- 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();}}}
}
- 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模型。