如何在 Java NIO 中刷新 SocketChannel?
在Java IO中,OutputStream
可以使用flush()
方法来确保数据立即发送。
Java NIO中是否有相应的函数 SocketChannel
?据我所知,FileChannel
有一个force()
方法来刷新数据。
可能是一个非常幼稚的问题......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OutputStream.flush()
除了刷新任何BufferedOutputStream
或ObjectOutputStream
或PrintStream
的缓冲区外,什么也不做。都在堆栈中。具体来说,它不会执行与
FileChannel.force()
或getFD().sync()
相对应的任何操作。它只是将流缓冲区从 JVM 刷新到(在本例中)内核中的套接字发送缓冲区。SocketChannel.write() 根本不涉及任何此类缓冲:它直接进入内核中的套接字发送缓冲区。所以没有什么可以flush的,所以没有flush操作。
OutputStream.flush()
does nothing except flush the buffers of anyBufferedOutputStream
s orObjectOutputStream
s orPrintStream
s that are in the stack.Specifically, it doesn't do anything corresponding to
FileChannel.force()
orgetFD().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.当您将数据强制写入磁盘时,操作系统可以确定数据已成功写入磁盘。然而,TCP 通信更加复杂,并且数据要经过操作系统控制之外的许多阶段。一般来说,操作系统会尽快结束数据,并且不会将套接字数据(通常约为 64 KB)缓冲到缓冲磁盘写入(有时为 GB)的程度。
确保已接收数据的最佳方法成功就是让另一端发送响应。
如果您希望尽可能快地发送数据,您可以尝试关闭 nagle,但是大多数操作系统在优化此方面都非常聪明,并且关闭它并不会像使用时那样产生太大的差异。
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.
使用
.force()
或.getFD.sync()
更新:由于您更新了您的问题以更具体地了解 SocketChannel(通常是 NIO),请参阅我的回复。
Use either
.force()
or.getFD.sync()
Update: Since you updated your question to be more specific on a SocketChannel (it was generally NIO), please see my reply instead.