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;
}
}