使用Boost Asio和C / C ++拒绝连接后,如何避免程序退出

时间:2011-06-06 10:53:47

标签: c++ exception-handling boost-asio

目前,我正在使用Boost Asio以通过TCP连接到服务器。

我使用条件案例来决定应用程序是否必须启动与服务器的连接;它工作得很好,但问题是,如果我在服务器关闭时尝试连接到服务器,那么应​​用程序崩溃会出现此错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
  what():  Connection refused

这是我正在使用的代码:

    case CONNECTION:
 // Connect to the server
 using boost::asio::ip::tcp;
 boost::asio::io_service io_service;
 tcp::resolver resolver(io_service);
 tcp::resolver::query query(tcp::v4(), server, boost::lexical_cast<string>(porta));
 tcp::resolver::iterator iterator = resolver.resolve(query);
 tcp::socket s(io_service); 
 s.connect(*iterator); 

我希望保持我的应用程序正常运行,并且只提示连接失败的警告。

如何处理此异常?

2 个答案:

答案 0 :(得分:8)

您应该使用try ... catch块。他们以这种方式工作:

try
{
    s.connect(*iterator);
}
catch (boost::system::system_error const& e)
{
    std::cout << "Warning: could not connect : " << e.what() << std::endl;
}

答案 1 :(得分:7)

根据文档here,失败connect会引发boost::system::system_error。因此,您需要在try...catch块中包装代码并捕获上述异常。或者,如果您不想使用异常,则可以使用描述为here的其他重载,该重载会在出错时返回错误代码。