简体   繁体   English

如何在 Java NIO 中刷新 SocketChannel?

[英]How to flush a SocketChannel in Java NIO?

In Java IO, an OutputStream can use flush() method to make sure data is sent at once.在 Java IO 中, OutputStream可以使用flush()方法来确保一次发送数据。

Is there a corresponding function in Java NIO for SocketChannel ? Java NIO 中有对应的SocketChannel函数吗? As far as I know, there is a force() method for FileChannel to flush data.据我所知, FileChannel有一个force()方法来刷新数据。

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. OutputStream.flush()除了刷新堆栈中任何BufferedOutputStreamObjectOutputStreamPrintStream的缓冲区外,什么都不做。

Specifically, it doesn't do anything corresponding to FileChannel.force() or getFD().sync() .具体来说,它不做任何与FileChannel.force()getFD().sync()对应的事情。 It just flushes stream buffers from the JVM into (in this case) the socket send buffer in the kernel.它只是将流缓冲区从 JVM 刷新到(在这种情况下)内核中的套接字发送缓冲区。

SocketChannel.write() doesn't involve any such buffering at all: it goes directly to the socket send buffer in the kernel. SocketChannel.write()根本不涉及任何此类缓冲:它直接进入内核中的套接字发送缓冲区。 So there is nothing to flush, so there is no flush operation.所以没有什么可以flush,所以没有flush操作。

When you force() the data to disk, the OS can determine it has been written to disk successfully.当您 force() 将数据写入磁盘时,操作系统可以确定它已成功写入磁盘。 However TCP communication is more complex and the data passes through many stages outside the OSes control.然而,TCP 通信更为复杂,数据经过操作系统控制之外的许多阶段。 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)一般来说,操作系统会尽快结束数据,并且不会像缓冲磁盘写入(有时是 GB)那样缓冲套接字数据(通常约为 64 KB)

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.如果您希望尽可能快地发送数据,您可以尝试关闭 nagle,但是大多数操作系统在优化此功能方面非常聪明,关闭它并没有像使用时那样产生太大的影响。

A SocketChannel cant't be flushed.无法刷新 SocketChannel。 You'll have to check wheter the data is sent completely instead.您必须检查数据是否完整发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM