I\'m using Boost.Asio for a server application that I\'m writing.
async_send requires the caller to keep ownership of the data that is being sent until
But now I'm wondering if I have multiple clients, will I need to create a separate vector for each connection?
Yes, though each vector does not need to be in global scope. The typical solution to this problem is to retain the buffer as a member of an object, and bind a member function of that object to a functor passed to the async_write completion handler. This way the buffer will be retained in scope throughout the lifetime of the asynchronous write. The asio examples are littered with this usage of binding member functions using this and shared_from_this. In general it is preferable to use shared_from_this to simplify object lifetime, especially in the face of io_service:stop() and ~io_service(). Though for simple examples, this scaffolding is often unnecessary.
The destruction sequence described above permits programs to simplify their resource management by using shared_ptr<>. Where an object's lifetime is tied to the lifetime of a connection (or some other sequence of asynchronous operations), a shared_ptr to the object would be bound into the handlers for all asynchronous operations associated with it.
A good place to start is the async echo server due to its simplicity.
boost::asio::async_write(
socket,
boost::asio::buffer(data, bytes_transferred),
boost::bind(
&session::handle_write,
this,
boost::asio::placeholders::error
)
);