I was able to reproduce a situation that may be similar to yours. I think, ironically, your recipient consumes data faster than you write it.
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); } }
If you start the above server, and then make the above client try to write 10 fragments of 128 kilobytes of data, you will see that each write operation writes the entire buffer without blocking. However, if you modify the above server so that you donβt read anything from the connection, you will see that only the first write operation on the client will write 128 kb, while all subsequent writes will return 0 .
Output when the server reads the connection:
to write: 131072, written: 131072 to write: 131072, written: 131072 to write: 131072, written: 131072 ...
Output when the server does not read the connection:
to write: 131072, written: 131072 to write: 131072, written: 0 to write: 131072, written: 0 ...
source share