开发者

How to flush a SocketChannel in Java NIO?

开发者 https://www.devze.com 2023-04-05 01:59 出处:网络
In Java IO, an OutputStream can use flush() method to make sure data is sent at once. Is there a corre开发者_运维知识库sponding function in Java NIO for SocketChannel? As far as I know, there is a fo

In Java IO, an OutputStream can use flush() method to make sure data is sent at once.

Is there a corre开发者_运维知识库sponding 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 BufferedOutputStreams or ObjectOutputStreams or PrintStreams 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.


A SocketChannel cant't be flushed. You'll have to check wheter the data is sent completely instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号