C++;ASIO:async_accept()处理程序在服务器销毁时引发异常 我正在开发一个基于C++的ASIO应用程序。指
我的服务器类:C++;ASIO:async_accept()处理程序在服务器销毁时引发异常 我正在开发一个基于C++的ASIO应用程序。指,c++,boost-asio,C++,Boost Asio,我的服务器类: class CServer { public: CServer(asio::io_service& io_service, const std::string serIdentity, std::string IP, const std::string port); ~CServer(); void listen(); void handle_accept(sessionPtr newSession, const asio::err
class CServer {
public:
CServer(asio::io_service& io_service, const std::string serIdentity, std::string IP, const std::string port);
~CServer();
void listen();
void handle_accept(sessionPtr newSession, const asio::error_code& error);
private:
tcp::acceptor acceptor_; // only in the listener
asio::io_service& io_;
CSerSessionsManager mng_;
};
void CServer::listen()
{
sessionPtr newSession = std::make_shared<channel::CSerSession>(io_, mng_, serIdentifier_, ip_, port_);
acceptor_.async_accept(newSession->socket(), std::bind(&CServer::handle_accept, this, newSession,
std::placeholders::_1));
}
void CServer::handle_accept(sessionPtr newSession, const asio::error_code& error)
{
if (!error)
{
//Do Something
listen();
}
else
{
DEBUG_MSG("Listen_Error");
//Returning from here throws Exception
}
}
我在会话类销毁方面也有类似的问题
当调用
~CServer()
时,如何解决此问题并确保干净退出。我建议查看各种Boost ASIO,因为它们比聊天示例更完整
关闭服务器对象的一种模式是使用handle\u stop
方法关闭接收器并关闭连接,例如,上面链接的单线程HTTP服务器示例中的以下内容:
void server::handle_stop()
{
// The server is stopped by cancelling all outstanding asynchronous
// operations. Once all operations have finished the io_service::run() call
// will exit.
acceptor_.close();
connection_manager_.stop_all();
}
在Boost示例中,这由Ctrl-C处理程序调用:
// Register to handle the signals that indicate when the server should exit.
// It is safe to register for the same signal multiple times in a program,
// provided all registration for the specified signal is made through Asio.
signals_.add(SIGINT);
signals_.add(SIGTERM);
#if defined(SIGQUIT)
signals_.add(SIGQUIT);
#endif // defined(SIGQUIT)
signals_.async_wait(boost::bind(&server::handle_stop, this));
但您可能希望从stop方法显式关闭,如:
void server::stop()
{
io_service_.post(boost::bind(&server::handle_stop, this));
}
如果您需要更多关于如何将其挂接的建议,我们需要查看ASIO代码的其余部分。如果
CServer
对象仍在侦听传入连接,为什么要销毁它?存在多个CServer
,因此当一个对象超出范围时handle\u accept()
会生成错误。如果调用acceptor.close()
并从handle\u accept
返回时,也会发生这种情况-引发异常。如何确保干净地销毁CServer类
通常,您可以确保CServer
s对象的生存期在执行工作(如侦听传入连接)时延长。这通常是通过继承enable\u shared\u from\u This
来实现的,一些Asio示例使用了这个概念。我尝试了你的建议,但仍然停留在同一点上,为了更好地理解这个问题,我简化了我的应用程序,并在这里问了一个问题。你能看一下吗?你能看看“温柔”吗
void server::stop()
{
io_service_.post(boost::bind(&server::handle_stop, this));
}