我设法重现了可能与您的情况相似的情况。我认为,具有讽刺意味的是,您的收件人使用数据的速度比您编写数据的速度要快。
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) throws Exception {
final ServerSocket ss = new ServerSocket(12345);
final Socket cs = ss.accept();
System.out.println("Accepted connection");
final InputStream in = cs.getInputStream();
final byte[] tmp = new byte[64 * 1024];
while (in.read(tmp) != -1);
Thread.sleep(100000);
}
}
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class MyNioClient {
public static void main(String[] args) throws Exception {
final SocketChannel s = SocketChannel.open();
s.configureBlocking(false);
s.connect(new InetSocketAddress("localhost", 12345));
s.finishConnect();
final ByteBuffer buf = ByteBuffer.allocate(128 * 1024);
for (int i = 0; i < 10; i++) {
System.out.println("to write: " + buf.remaining() + ", written: " + s.write(buf));
buf.position(0);
}
Thread.sleep(100000);
}
}
如果您运行上面的服务器,然后让上面的客户端尝试写入 10 个 128 kB 的数据块,您会看到每个写入操作都会写入整个缓冲区而不会阻塞。但是,如果您修改上面的服务器不从连接中读取任何内容,您会看到只有客户端上的第一个写入操作会写入 128 kB,而所有后续写入都将返回0
.
服务器从连接中读取时的输出:
to write: 131072, written: 131072
to write: 131072, written: 131072
to write: 131072, written: 131072
...
服务器未从连接中读取时的输出:
to write: 131072, written: 131072
to write: 131072, written: 0
to write: 131072, written: 0
...