【发布时间】:2011-10-28 01:42:25
【问题描述】:
我正在尝试编写一个程序,该程序将从充当服务器的摄像头请求某些信息,例如内部温度,对不起,如果我的术语不正确,但基本上我的意思是与摄像头是通过 HTTP 获取请求来实现的。该程序本质上只是从 boost 库中调用一个稍微适应的版本async_client,每次通过不同的路径来检查不同的值,然后比较返回的值以确保它在传递不同的路径以检查其他内容之前听起来合理。
代码似乎第一次运行正常,但在第二次尝试时,它会到达 handle_connect 函数并输出“错误:在已连接的套接字上发出连接请求”
函数如下所示:
void Async_client::handle_connect(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator)
{
http_deadline_timer_.cancel();
if (!err)
{
// The connection was successful. Send the request.
boost::asio::async_write(socket_, request_, boost::bind(&Async_client::handle_write_request, this,
boost::asio::placeholders::error));
//deadline timer stuff
http_deadline_timer_.expires_from_now( ::boost::posix_time::seconds(1));
http_deadline_timer_.async_wait( ::boost::bind(&Async_client::call_handle_deadline_timeout, this, boost::asio::placeholders::error));
}
else if (endpoint_iterator != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&Async_client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
//deadline timer stuff
http_deadline_timer_.expires_from_now( ::boost::posix_time::seconds(1));
http_deadline_timer_.async_wait( ::boost::bind(&Async_client::call_handle_deadline_timeout, this, boost::asio::placeholders::error));
}
else
{
LOG_WARN("Async_client.cpp: Error: " << err.message());
}
}
我尝试将这部分代码从 else if 语句复制到 else 语句中,并认为它会关闭套接字并重新运行 handle_connect 函数,但它似乎只是在端点 = *endpoint_iterator 行上崩溃到软件.
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint, boost::bind(&Async_client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
有人知道在这种情况下我应该怎么做吗?断开插座并重新连接?如果是这样,我该怎么做?
【问题讨论】:
-
在第一个函数的开始我添加了 socket_.close();每次使用 async_client 时关闭套接字。值得庆幸的是,这似乎并没有在第一次调用 async_client 时破坏任何东西,并且在第二次运行时,它似乎确实让它通过了 handle_connect 函数,但是它只到达了将 response_stream 读取为 0 的 handle_read_status_line,这是一个无效的响应,在程序的第一次运行中,response_stream 是 0x23f350。这些问题有关系吗?知道我能做些什么吗?
-
认为我已经设法通过添加“response_.consume(response_.size());”解决了这个问题在 socket_.close() 之后的第一个函数的开始处;线。这将清除作为 boost::asio::streambuf 的清除 response_。 @Sam Miller:你对我的帖子做了什么编辑?我想这并不重要,但如果我在问问题的方式上做错了什么,下次知道会很好。谢谢。
-
@meerkat 查看更改日志。我删除了你的告别词并添加了 boost-asio 标签。如果您已经解决了您的问题,请添加答案。
标签: c++ sockets boost-asio