c++ - 使用 boost asio 接收文本的最有效方式?

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

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

在我看来,将该 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;
    }       
}

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

关于c++ - 使用 boost asio 接收文本的最有效方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877287/

相关文章:

c++ - C++ 中变量的作用域最小化

c++ - boost::thread::join() 崩溃试图引用销毁的 thread_info

c++ - boost Asio : waiting until thread_group has processed all posted tasks?

boost - 使用 boost::asio 制作异步 udp 客户端

c++ - boost::asio 自定义处理程序分配

c++ - 如何让写时复制在 Linux 上的共享内存上工作

c++ - 可移植 "typeof"名称与外部链接

c++ - 检查文件名是有效的 Windows 名称

c++ - Boost 客户端无法从服务器接收消息

c++ - 使用 Boost.Qi 实现递归语法