right now i am receiving text in the following way:
boost::asio::streambuf buffer;
std::string text;
while(true) {
try
{
boost::asio::read_until(*m_pSocket, buffer, "END");
text = boost::asio::buffer_cast<const char*>(buffer.data());
buffer.consume(text.size());
boost::asio::write(*m_pSocket, boost::asio::buffer(text, text.size()));
std::cout << text<< std::endl;
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
break;
}
}
I just echo received text to the client when the sequence "END" was received. My question:
It seems to me very inefficent to convert that streambuf to a string and then to consume the text signs from it. What is the right way to work with the received data in a nice, clean and efficent way?
All together you will have two copies of the received text: one in the streambuf, the other in the string. The boost::asio::buffer
is just a pointer, pointing into the string, and a size.
If sending the pingback directly from the stringbuf is not an option, that is the best you can get. However, I don't see what should be the problem with first sending back the streambuf's content and consuming it afterwards for your internal use.
Your code could look like this then:
boost::asio::streambuf buffer;
while(true) {
try
{
auto size = boost::asio::read_until(*m_pSocket, buffer, "END");
//send back the seuqence:
auto begin = boost::asio::buffer_cast<const char*>(buffer.data());
boost::asio::write(*m_pSocket, boost::asio::buffer(begin, size));
//consume the content...
std::istream is(&buffer);
is >> /* whatever fits here... */
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
break;
}
}
Aside from that, I would not send back the whole sequence. Depending on the average size of the sequences sent, it could be better to calculate a checksum on the fly and send that back instead of the whole sequence.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.