java nio 中 socketchannel 的 write() 方法用于将数据从 bytebuffer 写入网络通道。由于网络 i/o 是非阻塞且不可靠的,单次调用 write() 并不保证能写完所有数据,因此必须在一个循环中检查返回值,直到缓冲区剩余量为零或发生异常。

如何确保 ByteBuffer 中的数据被完全发送
要确保数据全部发出,需要编写一个包装方法,在 while (buffer.hasRemaining()) 循环中持续调用 channel.write(buffer)。每次调用后,如果返回值为 -1,说明连接已关闭;如果返回值大于 0,则继续循环,直到缓冲区为空。这种方法能有效处理 TCP 粘包或半包情况下的数据分片发送问题。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class WriteExample {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost", 8080));
// 等待连接完成
while (!channel.finishConnect()) {
Thread.sleep(10);
}
String msg = "Hello";
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
writeAll(channel, buffer);
}
private static void writeAll(SocketChannel ch, ByteBuffer buf) throws IOException {
while (buf.hasRemaining()) {
int written = ch.write(buf);
if (written == -1) {
throw new IOException("Connection closed");
}
}
}
}
非阻塞模式下 write 返回 0 时如何处理
在非阻塞模式下,如果 write() 返回 0,表示当前没有可用的空间来写入任何字节。此时不应抛出异常,而应暂停写入操作,通常通过注册 OP_WRITE 事件到 Selector 上,等待通道变为可写状态后再继续写入。这避免了忙等待(Busy Waiting)导致的 CPU 资源浪费。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.HashSet;
public class NonBlockingWriteHandler {
private Selector selector;
private SocketChannel channel;
private ByteBuffer buffer;
private Set<SelectionKey> keysToWrite = new HashSet<>();
public void init() throws IOException {
selector = Selector.open();
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new java.net.InetSocketAddress("localhost", 8080));
channel.register(selector, SelectionKey.OP_CONNECT);
buffer = ByteBuffer.allocate(1024);
}
public void handleWrite(SelectionKey key) throws IOException {
SocketChannel ch = (SocketChannel) key.channel();
while (buffer.hasRemaining()) {
int written = ch.write(buffer);
if (written == 0) {
break; // 无空间可写,等待 OP_WRITE
}
}
if (!buffer.hasRemaining()) {
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
}
}
}
当 write 返回 -1 时意味着什么
当 write() 方法返回 -1 时,意味着对端已经正常关闭了连接。此时继续向该通道写入数据将导致 ClosedChannelException。开发者应当捕获这一信号,清理相关资源,并停止对该通道的后续读写操作。这是 TCP 协议中 FIN 包到达后的标准行为,表明流的一端已经结束发送。

















