使用 boost asio 接收文本最有效的方法?

Ano*_*ous 5 c++ boost boost-asio

现在我通过以下方式收到短信:

    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;
        }       
    }
Run Code Online (Sandbox Code Playgroud)

当收到序列“END”时,我只是将收到的文本回显给客户端。我的问题:

在我看来,将该streambuf转换为字符串然后使用其中的文本符号的效率非常低。以良好、干净和高效的方式处理接收到的数据的正确方法是什么?

Arn*_*rtz 2

总之,您将拥有所接收文本的两份副本:一份在 Streambuf 中,另一份在字符串中。它boost::asio::buffer只是一个指向字符串的指针和一个大小。

如果不能直接从 stringbuf 发送 pingback,那么这是最好的选择。但是,我不明白首先发回 Streambuf 的内容并随后将其用于内部使用会出现什么问题。

那么你的代码可能如下所示:

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;
    }       
}
Run Code Online (Sandbox Code Playgroud)

除此之外,我不会发回整个序列。根据发送序列的平均大小,最好动态计算校验和并将其发回,而不是发送整个序列。