【问题标题】:How to read to asio buffer say `1` byte from one socket and than `read_some` more from another?如何从一个套接字读取到 asio 缓冲区说“1”字节,而不是从另一个套接字读取“read_some”?
【发布时间】:2023-03-15 12:48:01
【问题描述】:

所以我正在尝试实现定时 http 连接 Keep-Alive。而且我需要能够在超时时杀死它。所以目前我有(或者至少我想有):

void http_request::timed_receive_base(boost::asio::ip::tcp::socket& socket, int buffer_size, int seconds_to_wait, int seconds_to_parse)
{
    this->clear();

    http_request_parser_state parser_state = METHOD;

    char* buffer = new char[buffer_size];
    std::string key = "";
    std::string value = "";
    boost::asio::ip::tcp::iostream stream;
    stream.rdbuf()->assign( boost::asio::ip::tcp::v4(), socket.native() );
    try
    {
        do
        {
            stream.expires_from_now(boost::posix_time::seconds(seconds_to_wait));
            int bytes_read = stream.read_some(boost::asio::buffer(buffer, buffer_size));
            stream.expires_from_now(boost::posix_time::seconds(seconds_to_parse));
            if (stream) // false if read timed out or other error
            {
                parse_buffer(buffer, parser_state, key, value, bytes_read);
            }
            else
            {
                throw std::runtime_error("Waiting for 2 long...");
            }


        } while (parser_state != OK);
    }
    catch (...)
    {
        delete buffer;
        throw;
    }
    delete buffer;
}

但是tcp::iostream中没有read_some,所以编译器给了我一个错误:

Error   1   error C2039: 'read_some' : is not a member of 'boost::asio::basic_socket_iostream<Protocol>'    

这就是为什么我想知道 - 如何通过 stream.read(如 stream.read(buffer, 1);)读取 1 个字节,而不是通过套接字 API 将 read_some 读取到该缓冲区(看起来像 int bytes_read = socket.read_some(boost::asio::buffer(buffer, buffer_size));,然后调用我的 @987654327 @函数具有真正的bytes_read值)

顺便说一句,最后一个字节似乎会有一个非常可悲的问题..(

【问题讨论】:

    标签: c++ boost tcp boost-asio keep-alive


    【解决方案1】:

    抱歉有点粗略,但您阅读过文档吗?套接字 iostream 应该像普通的 iostream 一样工作,如 cincout。只需执行stream &gt;&gt; var。也许你想改用basic_stream_socket::read_some

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2010-10-30
      • 2012-09-25
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多