本文共 4319 字,大约阅读时间需要 14 分钟。
Buffer(缓冲区)是NIO中用于高效读写数据的核心组件。它通过将数据从通道读入缓冲区,再从缓冲区写入通道,简化了数据传输过程。应用程序在发送数据时,会先将数据写入缓冲区,然后通过通道发送;在接收数据时,先从通道读取到缓冲区,再逐个读取缓冲区数据。
Capacity(容量)
Buffer的容量决定了可以存储的最大数据量。只能往Buffer中写入capacity个字节、长整型或字符。一旦Buffer满了,需要通过clear()或compact()方法清空。Position(位置)
表示当前在缓冲区中可以写入或读取的位置。初始值为0,写入或读取数据后,position会移动到下一个可写入或可读的位置。Limit(限制)
在写模式下,limit表示缓冲区中可以写入的最大数据量,等于capacity。切换到读模式后,limit表示可以读取的最大数据量。分配
使用allocate()方法分配内存,例如:ByteBuffer buf = ByteBuffer.allocate(1024);
读写操作
其他操作
Selector(选择器)用于管理和监听多个通道(Channel)的读写事件。它通过注册事件类型(如OP_READ、OP_WRITE)来判断何时需要处理哪个通道。
Channel是NIO中用于高效读写数据的核心类。常见的Channel实现包括SocketChannel和ServerSocketChannel,它们都继承自SelectableChannel。所有通道都需要通过Buffer进行数据传输。
SelectionKey用于表示对特定通道的操作事件感兴趣。定义了四种事件类型:OP_ACCEPT、OP_READ、OP_WRITE、OP_CONNECT。这些事件类型对应不同的网络操作。
服务端启动
使用ServerSocketChannel创建服务器,并注册OP_ACCEPT事件处理器。客户端连接
客户端通过SocketChannel连接到服务器,并注册OP_CONNECT事件处理器。数据交互
IO循环处理
使用Selector管理多个通道,等待事件就绪。每次循环中,调用select()方法阻塞等待事件,然后处理对应的事件。public class NioServer { private static Selector selector; private static ServerSocketChannel serverChannel; public static void main(String[] args) { try { selector = Selector.open(); serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); serverChannel.socket().bind(new InetSocketAddress(8080)); serverChannel.register(selector, SelectionKey.OP_ACCEPT); startServer(); } catch (IOException e) { e.printStackTrace(); } } private static void startServer() { while (!Thread.currentThread().isInterrupted()) { try { selector.select(); Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } } } catch (IOException e) { e.printStackTrace(); } } }} public class NioClient { private static Selector selector; private static SocketChannel socketChannel; public static void start() { try { selector = Selector.open(); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_CONNECT); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { start(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请输入消息:"); String msg = scanner.nextLine(); if (!sendMsg(msg)) { break; } } } private static boolean sendMsg(String msg) { try { socketChannel.register(selector, SelectionKey.OP_READ); ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); buffer.flip(); int bytesWritten = socketChannel.write(buffer); return bytesWritten > 0; } catch (IOException e) { e.printStackTrace(); return false; } }} Reactor模式通过多个Reactor线程管理IO操作,提升了吞吐量和系统性能。其核心思想是将IO事件分散到多个线程,从而避免单线程处理大量IO请求带来的性能瓶颈。
流程
优化
局限性
流程
优势
应用
通过以上优化,NIO网络编程实现了高效的数据传输和事件处理,适用于各种网络应用场景。
转载地址:http://cjcfk.baihongyu.com/