[英]Most efficient way to receive text with boost asio?
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. 当接收到序列“ END”时,我只是将接收到的文本回显到客户端。 My question:
我的问题:
It seems to me very inefficent to convert that streambuf to a string and then to consume the text signs from it. 在我看来,将该streambuf转换为字符串,然后从中消耗文本符号的效率很低。 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. 总之,您将收到接收到的文本的两个副本:一个在streambuf中,另一个在字符串中。 The
boost::asio::buffer
is just a pointer, pointing into the string, and a size. boost::asio::buffer
只是一个指向字符串和大小的指针。
If sending the pingback directly from the stringbuf is not an option, that is the best you can get. 如果不能直接从stringbuf发送pingback,那将是最好的选择。 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.
但是,我看不到先发回streambuf的内容并在以后供内部使用时会出现什么问题。
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.
取决于发送的序列的平均大小,最好是即时计算校验和,然后将其发送回而不是整个序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.