简体   繁体   English

可靠地写入Java SocketChannel

[英]Reliable write to Java SocketChannel

I'd have a question regarding java SocketChannel. 我对Java SocketChannel有疑问。

Say I have a socket channel opened in blocking mode; 假设我有一个以阻塞模式打开的套接字通道; after calling the the write(ByteBuffer) method, I get an integer describing how many bytes were written. 调用write(ByteBuffer)方法后,我得到一个整数,描述写入了多少个字节。 The javadoc says: "Returns: The number of bytes written, possibly zero" javadoc说: “返回:写入的字节数,可能为零”

But what exactly does this mean? 但这到底什么意思? does this mean that the number of bytes really has been delivered to the client (so that sender received tcp ack making evident how many bytes have been received by server), or does this mean that the number of bytes has been written to the tcp stack? 这是否意味着确实已将字节数传递给客户端(以便发送方接收到tcp ack,从而表明服务器已接收了多少字节),或者这意味着字节数已被写入tcp堆栈? (so that some bytes still might be waiting eg in the network card buffer). (以便某些字节可能仍在等待,例如在网卡缓冲区中)。

does this mean that the number of bytes really has been delivered to the client 这是否意味着确实已将字节数交付给客户端

No. It simply means the number of bytes delivered to the local network stack. 否。它只是表示传递到本地网络堆栈的字节数。

The only way to be sure that data has been delivered to the remote application is if you receive an application level acknowledgment for the data. 确保数据已传递到远程应用程序的唯一方法是,如果您收到数据的应用程序级别确认。

The paragraph that confuses you is for non-blocking I/O. 令您困惑的段落是非阻塞I / O。

For non-blocking operation, your initial call may indeed not write anything at the time of the call. 对于非阻塞操作,您的初始调用在调用时实际上可能未写入任何内容。

Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. 除非另有说明,否则只有在写完所有r个请求的字节之后,写操作才会返回。 Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. 根据其状态,某些类型的通道可能只写入某些字节,或者可能根本不写入。 A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer. 例如,处于非阻塞模式的套接字通道写入的字节数不能超过套接字输出缓冲区中的可用字节数。

As you can see, for blocking I/O all bytes would be sent ( or exception thrown in the middle of the send ) 如您所见,为了阻止I / O,将发送所有字节(或在send中间抛出异常)。

Note, that there is no guarantee on when bytes will appear on the receiving side, this is totally up to the low level socket protocol. 注意,不能保证字节何时会出现在接收端,这完全取决于底层套接字协议。

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

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