When use async_write_some and async_write

浪子不回头ぞ 提交于 2019-12-11 16:52:35

问题


I was reading the documentation of Boost Asio and it says that

boost::asio::async_write_some may NOT transfer all of the data to the peer. Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes.

So here is my question, in which cases should we use them, isn`t VERY important to ensure that all the data is written?! when to use async_write_some just this function seems to me useless?


回答1:


async_write is useful in request-reply mode when you need to send a specific response that fully fits in your buffer. I.e. when you switch to reading mode after the message is sent.

But if you need to send more data than you have in your write buffer then it doesn't matter if the whole buffer is sent or not, because you still have more data to send. In that case ensuring that the whole buffer is sent is going to be inefficient because the last chunk may be smaller than it could have been if you just called async_write_some in a loop, filling up the buffer with more data as you go. For optimal performance you want to ensure there is always enough data in the send buffer to fill a full frame.




回答2:


When you are asynchronously reading from one place, and writing to another, you probably just want to shove some bytes to the destination, and want to know when there is room in the buffer to send some more. You only need to use async_write for the last write (when you know there is no more to send)



来源:https://stackoverflow.com/questions/47366762/when-use-async-write-some-and-async-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!