如何在 Java NIO 中刷新 SocketChannel?

发布于 2024-12-05 01:31:37 字数 333 浏览 0 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独难免 2024-12-12 01:31:37

OutputStream.flush() 除了刷新任何 BufferedOutputStreamObjectOutputStreamPrintStream 的缓冲区外,什么也不做。都在堆栈中。

具体来说,它不会执行与 FileChannel.force()getFD().sync() 相对应的任何操作。它只是将流缓冲区从 JVM 刷新到(在本例中)内核中的套接字发送缓冲区。

SocketChannel.write() 根本不涉及任何此类缓冲:它直接进入内核中的套接字发送缓冲区。所以没有什么可以flush的,所以没有flush操作。

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.

如此安好 2024-12-12 01:31:37

当您将数据强制写入磁盘时,操作系统可以确定数据已成功写入磁盘。然而,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.

小糖芽 2024-12-12 01:31:37

使用 .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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文