Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Asio: The difference between async_read and async_receive

Tags:

c++

c++11

boost

What's the difference between async_read and async_receive?

like image 770
Clark Gaebel Avatar asked Jun 05 '10 23:06

Clark Gaebel


2 Answers

async_receive is a function that just receives into a buffer, but may not receive the amount you asked for. (It'll be equal or less, never more.)

async_read, however, will always receive the amount you asked for, as it states:

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

The only thing the page is a bit vague on is what async_read does if it doesn't get that many bytes, and the connection closes gracefully. (Does that count as "error"?) This can probably be determined with a quick test. (async_receive, however, would just give you what it got.)

like image 50
Thanatos Avatar answered Nov 19 '22 19:11

Thanatos


The first is a free function, the second is a member function.

Another difference is socket_base::message_flags flags parameter. See possible values, for example, in the recv(2) manual page.

Edit:

With async_receive you need to check how many bytes you got. Use it if you want to read at max N bytes, vs. exactly N bytes with async_read. Sorry, thought that was sort of obvious from boost docs.

like image 45
Nikolai Fetissov Avatar answered Nov 19 '22 20:11

Nikolai Fetissov