我发现很多例子展示了如何将boost :: beast :: multi_buffer的内容复制到字符串中,但是如何将字符串的内容分配给之前在类实例中创建的multi_buffer?
如果我在班上有示例声明:
private:
boost::beast::websocket::stream<boost::asio::ip::tcp::socket> ws_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::beast::multi_buffer buffer_;
如何在调用之前将字符串分配给buffer_:
ws_.async_write(buffer_.data(), boost::asio::bind_executor(strand_,
std::bind(&CNXG_session::on_write,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
答案 0 :(得分:7)
您还可以使用boost::beast::ostream
功能将DynamicBuffer转换为您可以写入的std::ostream
:
boost::beast::multi_buffer b;
boost::beast::ostream(b) << "Hello, world!\n";
答案 1 :(得分:3)
您可以在prepare
之后使用boost::asio::buffer_copy
:
size_t n = buffer_copy(b.prepare(contents.size()), boost::asio::buffer(contents));
<强> Live On Coliru 强>
#include <iostream>
#include <boost/asio/buffers_iterator.hpp>
#include <boost/beast.hpp>
using boost::beast::multi_buffer;
void dump_buffer(std::ostream& os, multi_buffer const& mb) {
os << mb.size() << " (" << mb.capacity() << ") "
<< "'" << boost::beast::buffers(mb.data()) << "'\n";
}
int main() {
boost::beast::multi_buffer b;
dump_buffer(std::cout << "before: ", b);
std::string const contents = "Hello world";
size_t n = buffer_copy(b.prepare(contents.size()), boost::asio::buffer(contents));
b.commit(n);
dump_buffer(std::cout << "after: ", b);
}
打印
before: 0 (0) ''
after: 11 (512) 'Hello world'
注意:也许您会对Boost asio 1.66.0中的新缓冲设施感兴趣:dynamic_buffer
(Dynamically sized boost::asio::buffer)