我正在尝试编写一个程序,该程序将从充当服务器的摄像机中请求某些信息,例如内部温度,抱歉,如果我的术语不正确,但基本上我的意思是实现了与摄像机的通信通过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 并重新连接?如果是这样,我该怎么做?
最佳答案
也许将SO_REUSEADDR
选项与setsockopt
一起使用可能会有所帮助。
关于c++ - “Error: A connect request was made on an already connected socket”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7910605/