Boost.Asio async_send问题 [英] Boost.Asio async_send question
问题描述
我正在为我撰写的服务器应用程序使用Boost.Asio。
I'm using Boost.Asio for a server application that I'm writing.
async_send
调用者保持正在发送的数据的所有权,直到数据成功发送。这意味着我的代码(看起来像下面的)会失败,它会失败,因为 data
将不再是一个有效的对象。
async_send
requires the caller to keep ownership of the data that is being sent until the data is sent successfully. That means my code (which looks like the following) will fail, and it does, because data
will no longer be a valid object.
void func()
{
std::vector<unsigned char> data;
// ...
// fill data with stuff
// ...
socket.async_send(boost::asio::buffer(data), handler);
}
$ b
所以我的解决方案是这样做:
So my solution was to do something like this:
std::vector<unsigned char> data;
void func()
{
// ...
// fill data with stuff
// ...
socket.async_send(boost::asio::buffer(data), handler)
}
$ b b
但现在我想知道我是否有多个客户端,我需要为每个连接创建一个单独的向量吗?
But now I'm wondering if I have multiple clients, will I need to create a separate vector for each connection?
或者我可以使用一个向量?如果我能够使用那个单一的向量,如果我覆盖其中的内容,会把我发送给所有的客户的数据弄乱了?
Or can I use that one single vector? If I'm able to use that single vector, if I overwrite the contents inside it will that mess up the data I'm sending to all my clients?
推荐答案
可能的解决方法是使用 shared_ptr
来保存您的本地向量
处理程序的签名接收 shared_ptr
,以便延长数据
的生命,直到发送完成(感谢Tim指向我):
A possible fix would be to use a shared_ptr
to hold your local vector
and change the handler's signature to receive a shared_ptr
so to prolong the life of the data
until the sending is complete (thanks to Tim for pointing that out to me):
void handler( boost::shared_ptr<std::vector<char> > data )
{
}
void func()
{
boost::shared_ptr<std::vector<char> > data(new std::vector<char>);
// ...
// fill data with stuff
// ...
socket.async_send(boost::asio::buffer(*data), boost:bind(handler,data));
}
这篇关于Boost.Asio async_send问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!