0

I'm looking for a design suggestion here. If we are using socket.async_write, the client code which is sending the message won't have a synchronous result to know if it succeeded or failed, and therefore doesn't know if it should retry sending (or whatever error handling would be invoked when a message failed to send.)

The boost docs say:

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

  • All of the data in the supplied buffers has been written. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

The callback method will tell you both where there was an error, and also number of bytes actually written (which if less than buffer size, indicates an error).

So it seems like you need to keep a copy of any message until you get notified it was sent, either to try a resend or to notify calling code that the message didn't get sent.

Is there any way to pass to the async handler method a reference to the buffer/message which was being sent? Or would a better approach to maintain some container of messages being written, and then pop it out when the async write completes?

Sam Goldberg
  • 6,711
  • 8
  • 52
  • 85

1 Answers1

2

If you look at the async-examples in the boost::asio (or the c++11 version) documetation, for example the chat message client, you can see there are three write methods. First there is a container used:

typedef std::deque<chat_message> chat_message_queue;
...
chat_message_queue write_msgs_;

If you write a message you call chat_client::write(message) which asynchronously calls chat_client::do_write which is calling chat_client::handle_write after sending data finished. Only the handle_write member-function is popping the message out of the deque, so there you can see, the message is still available even if an error occured.

Or would a better approach to maintain some container of messages being written, and then pop it out when the async write completes?

I would prefer to use a countainer and pop it if the message has been sent or use it to print out an error.


Edit:

In the C++11 version the chat_client::handle_write is missing, it is done in the do_write method using a lambda-function, but it still has the same behaviour.

user1810087
  • 5,146
  • 1
  • 41
  • 76
  • Thanks. I did review the chat_client and noticed the queue for storing messages. I wasn't sure if there was some other error callback mechanism that I was missing. – Sam Goldberg Jul 05 '13 at 17:41