Having a hard time understanding a few concepts with Boost ASIO TCP with async_read and async_write

后端 未结 1 825
逝去的感伤
逝去的感伤 2021-02-10 21:59

I\'m having a hard time understand the correct way I should structure a tcp client when using async_read and async_write. The examples seem to do a async_read after connecting

相关标签:
1条回答
  • 2021-02-10 22:24

    Conceptually, async_read waits for data to be received. You should call it any time you want something to happen after data is received and a read isn't already pending. Similarly, async_write waits for data to be written. You should call it any time you need to write data and a write isn't already pending.

    You should call async_read when you complete the connection. Before your async_read handler returns, it should probably call async_read again.

    When you need to write to the connection, you should call async_write (if a write isn't already pending). In your async_write handler, if you still need to write more, you should call async_write again.

    If no read is already pending, you can call async_read in your write handler, if you wish to resume reading after you finish writing. You can also just keep a read always pending. That's up to you.

    You should not check if there's anything to read before calling async_read. The point of async_read is for it to complete when there's something to read. It's a smart way of waiting and doing other things in the meantime.

    0 讨论(0)
提交回复
热议问题