Search code examples
c++boostboost-asio

write_some vs write - boost asio


Why do someone want to use write_some when it may not transmit all data to peer?

from boost write_some documentation

The write_some operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

What is the relevance of write_some method in boost when it has write method? I went through the boost write_some documentation,nothing I can guess.


Solution

  • At one extreme, write waits until all the data has been confirmed as written to kernel buffers for delivery to the remote system. It gives the greatest certainty of successful completion at the expense of being the slowest.

    At the opposite extreme, you could just queue the data for ASIO to write to a kernel buffer, and return immediately. This is fast, but gives no assurance at all that the data will actually be written. If a router was down, a DNS giving incorrect addresses, etc., you could be trying to send to some machine that isn't available and (possibly) hasn't been for a long time.

    write_some is kind of a halfway point between these two extremes. It doesn't return until at least some data has been written to a kernel buffer. It doesn't assure you that all the data will be written but may complete faster, and still gives a little bit of a "warm fuzzy" feeling that the write is likely to complete.

    As to when you'd likely want to use it: the obvious scenario would be something like a large transfer over a local connection on a home computer. The likely problem here isn't with the hardware, but with the computer (or router) being mis-configured. To get to the point of having a kernel buffer to write to, the system has (more or less) confirmed that the network stack is functioning and it's found (what it believes is) the address of the remote system, so there's a pretty good chance the rest will work as expected.

    As to when you'd want to avoid it: pretty much reverse the circumstances above. You're sending a small amount of data over (for example) an unreliable Internet connection. Since you're only sending a little data, you don't save much time by returning before all the data's sent. The connection is unreliable enough that the odds of a packet being transmitted are effectively independent of the odds for other packets--that is, sending one packet through tells you little about the likelihood of being able to send the next.