简体   繁体   中英

Reliable write to Java SocketChannel

I'd have a question regarding 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. The javadoc says: "Returns: The number of bytes written, possibly zero"

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? (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.

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. 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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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