1. 问题
很容易找到代码,boost::asio使用async_read_until配合boost::regex读取数据。但是却不知道怎么把数据从buf中读取出来。大部分示例中只有
boost::streambuf buf;
/*......*/
/*when read */
cout << &buf << endl;
但是如果不cout,而是将buf的数据转到我们自己设计的变量就不知道如何是好了。
2. 解决办法
boost::streambuf可以输入到std::stringstream。std::string可以用std::stringstream::str()获得
3. 代码示例
另外,也可以看到handle_read的参数bytes_read,streambuf:size(), streambuf转换成的std::string的长度都不一样。所以要对std::string做剪切。
/*初始化部分*/
boost::streambuf m_streambuf;
boost::regex m_regex("^{.*}$");
/*handle_read*/
void handle_read(const boost::system::error_code& error, size_t bytes_transferred) {
cout << __FUNCTION__ << endl;
if (!error) {
cout << bytes_transferred << " bytes have read " << "m_streambuf.size()=" << m_streambuf.size() << endl;
size_t i = 0;m_streambuf.commit(bytes_transferred);
stringstream ss;
ss << &m_streambuf;
std::string word = ss.str();
const size_t szWord = word.size();
cout << "word.size()=" << szWord << endl;
word.resize(bytes_transferred);
const size_t szWord2 = word.size();
cout << word << endl;
for (auto it = word.begin(); i < szWord2; it++, i++) {
if (*it >= 33 && *it <= 126) {
cout << *it << " ";
}else {
cout << '\\' << int(*it) << " ";
}
}
cout << endl;
cout << &m_streambuf << endl;
m_streambuf.consume(m_streambuf.size());
boost::asio::async_read_until(socket_, m_streambuf, m_reg, boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}else {
cerr << error.message() << endl;
}
}