在 java nio 中,op_write 用于注册通道可写事件。当通道缓冲区有空间或连接建立后,selector 会通知该 key 处于可写状态。开发者应在 selectionkey.iswritable() 为 true 时执行写入操作,并在发送完数据后取消 op_write 注册以避免无效唤醒。

如何正确注册和触发 OP_WRITE 事件
要使用 OP_WRITE,必须在 Selector 中通过 register() 方法将其与 SelectionKey 关联。通常,在连接建立(OP_CONNECT)成功后,如果客户端需要立即发送数据,应注册 OP_WRITE。当 Selector 的 select() 返回且 key.isWritable() 为真时,即可调用通道的 write() 方法。

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.SocketChannel;
import java.util.Iterator;
public class WriteExample {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost", 8080));
// 初始注册连接事件
channel.register(selector, SelectionKey.OP_CONNECT);
while (true) {
int n = selector.select();
if (n == 0) continue;
Iterator<selectionkey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isConnectable()) {
channel.finishConnect();
// 连接成功后,注册写事件
channel.register(selector, SelectionKey.OP_WRITE);
} else if (key.isWritable()) {
ByteBuffer buffer = ByteBuffer.wrap("Hello Server".getBytes());
channel.write(buffer);
if (!buffer.hasRemaining()) {
// 数据发送完毕,取消写事件注册
channel.register(selector, 0);
}
}
}
}
}
}</selectionkey>
上述代码展示了从连接到注册的完整流程。注意 channel.register(selector, 0) 用于停止监听写事件,防止 CPU 空转。
什么情况下 OP_WRITE 会失效或导致问题
OP_WRITE 并非总是有效。在 TCP 连接未完全建立前,或者本地发送缓冲区已满时,isWritable() 可能返回 false。此外,如果频繁注册和注销 OP_WRITE 会导致上下文切换开销。最佳实践是仅在缓冲区有空闲空间时才注册,并在发送完成后立即注销。

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.SocketChannel;
import java.util.Iterator;
public class BufferFullExample {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost", 8080));
channel.register(selector, SelectionKey.OP_CONNECT);
while (true) {
int n = selector.select();
if (n == 0) continue;
Iterator<selectionkey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isConnectable()) {
channel.finishConnect();
channel.register(selector, SelectionKey.OP_WRITE);
} else if (key.isWritable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 大缓冲区
int written = channel.write(buffer);
if (written <p>此示例处理了缓冲区未满的情况。当 <code>write()</code> 返回的值小于请求量时,说明缓冲区已满,需保留 <code>OP_WRITE</code> 注册以便后续继续发送。</p>
<h2>基于程序中 OP_WRITE 注册时机对性能的影响</h2>
<p>在上面的代码中,<code>OP_WRITE</code> 的注册时机直接影响性能。如果在连接建立后立即注册,而数据尚未准备好,会导致不必要的 Selector 唤醒。正确的做法是在数据准备就绪后再注册,或在发送完毕后立即注销。这减少了无效的事件轮询,提高了吞吐量。</p></selectionkey>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











