tags:

views:

161

answers:

2

What's the difference between async_read and async_receive?

+1  A: 

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.

Nikolai N Fetissov
When would I use one over the other?
Clark Gaebel
"Consider using the async_read function if you need to ensure that the requested amount of data is received before the asynchronous operation completes."
Thanatos
So does that mean if I use async_recieve, I might not get all my data, but the error flag will say everything's fine? I'm not really sure what that line means.
Clark Gaebel
From async_recieve's link: "The receive operation may not receive all of the requested number of bytes." So, yes. Network stuff typically works this way: You might not get everything you asked for (the other side didn't send it, it's still in transit, etc.) async_read is a convenience function that will keep trying for you, if you know you want X bytes.
Thanatos
That's perfect, thank you. Mind putting that in an answer so I can accept it?
Clark Gaebel
Yes, 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* (`async_read`).
Nikolai N Fetissov
+2  A: 

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

Thanatos
In response to my own question: If async_read doesn't get the number of bytes because the stream closed gracefully before the requested size was obtained, the read handler gets invoked with an error of boost::asio::error::eof.
Thanatos