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

Mar*_*net 7 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
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的代码:

    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); 
Run Code Online (Sandbox Code Playgroud)

我想保持我的应用程序正常行为,并只提示连接失败的警告.

我该如何处理这个异常?

use*_*016 8

你应该使用try ... catch块.他们这样工作:

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


Ash*_*sha 7

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