In Java IO, an OutputStream
can use flush()
method to make sure data is sent at once.
Is there a corresponding function in Java NIO for SocketChannel
? As far as I know, there is a force()
method for FileChannel
to flush data.
Might be a very naive question...
OutputStream.flush()
does nothing except flush the buffers of any BufferedOutputStream
s or ObjectOutputStream
s or PrintStream
s that are in the stack.
Specifically, it doesn't do anything corresponding to FileChannel.force()
or getFD().sync()
. It just flushes stream buffers from the JVM into (in this case) the socket send buffer in the kernel.
SocketChannel.write()
doesn't involve any such buffering at all: it goes directly to the socket send buffer in the kernel. So there is nothing to flush, so there is no flush operation.
When you force() the data to disk, the OS can determine it has been written to disk successfully. However TCP communication is more complex and the data passes through many stages outside the OSes control. Generally speaking, the OS wills end out the data as soon as possible and won't buffer the socket data (typically about 64 KB) to the degree it will buffer disk writes (sometimes GBs)
The best way to ensure the data has been received successfully is to have the other end send a response.
If you want data to be sent as fast as possible you can try turning nagle off, however most OSes are pretty smart at optimising this and turning it off doesn't make as much difference as it used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With