【发布时间】: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