C++ 套接字已关闭,但会话引用未正确销毁
我正在使用boost::asio编写一个多线程服务器。有一个包含X个线程的池,根据示例使用异步读写 服务器结构如下所示: 服务器 管理程序线程并启动异步会话,为每个新客户端创建新会话 一场 表示客户端本身。从她的socketclient获取套接字引用并管理异步读取和异步写入。还有超时管理 有时,客户端的硬件设备冻结,我的服务器没有他的答复。为了解决这个问题,我阅读了有关使用异步等待和截止时间计时器的文章,并将其应用到我的软件中,但发生了一些奇怪的事情: 当发生正常断开连接时,异步操作将被取消,并出现操作中止错误,会话对象将被销毁。但是当设备冻结时,套接字将关闭,但会话对象不会被销毁,其实例仍保留在内存中,即使socket.close已被调用 我简化了代码并放在下面: 服务器.h server.cpp 会议h session.cpp 异步\u等待超时处理程序应该取消未完成的异步\u读取,而不是仅仅关闭套接字,否则套接字将保持打开状态C++ 套接字已关闭,但会话引用未正确销毁,c++,boost,boost-asio,C++,Boost,Boost Asio,我正在使用boost::asio编写一个多线程服务器。有一个包含X个线程的池,根据示例使用异步读写 服务器结构如下所示: 服务器 管理程序线程并启动异步会话,为每个新客户端创建新会话 一场 表示客户端本身。从她的socketclient获取套接字引用并管理异步读取和异步写入。还有超时管理 有时,客户端的硬件设备冻结,我的服务器没有他的答复。为了解决这个问题,我阅读了有关使用异步等待和截止时间计时器的文章,并将其应用到我的软件中,但发生了一些奇怪的事情: 当发生正常断开连接时,异步操作将被取消,并
void Session::handleDeadlineAsyncWait(boost::asio::deadline_timer* deadline)
{
if (this->stopped())
return;
if (deadline->expires_at() <= boost::asio::deadline_timer::traits_type::now())
{
boost::system::error_code sdEc;
this->getSocket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, sdEc);
this->getSocket().cancel(); // <-- add this
}
else
{
deadline->async_wait(
this->_strand.wrap(boost::bind(
&Session::handleDeadlineAsyncWait,
shared_from_this(),
deadline
))
);
}
}
此外,在Session::HandlerRead处理程序中,您应该检测到boost::asio::error::operation\u中止错误,因为这意味着读取被取消。我刚刚发现了问题 错误在函数Session::querywrite中 session.cpp 我移除了非空输出队列,并使用另一种方法,使用pushPack方法来做同样的事情 问题是async_wait调用了queueWrite方法,他自己调用了另一个async_wait,但最后期限计时器过期,造成处理器开销,并防止会话自毁
感谢@Sam Miller的贡献。超时时,您可以调用shutdown,但不要调用close。这是事实,但关机是一种优雅地关闭连接的方式。如果一切顺利,这不是问题。几分钟前我编辑了这篇文章以防止出现这种情况,之后我才发现了错误。谢谢你,谢谢,这就够了。但同样的错误还在继续。实际上,当我调用shutdown时,我会等待一切顺利,因为我没有调用cancel,但这次我调用另一个async_wait处理程序再次等待,以调用Session::disconnect方法。我现在将更新帖子正文上的代码。
#include "server.hpp"
Server::Server(boost::asio::io_service& io_service):
_io_service(io_service), _signals(io_service)
{
this->_endpoint = new boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), config.getServer().port);
this->_acceptor = new boost::asio::ip::tcp::acceptor(io_service);
this->_acceptor->open(boost::asio::ip::tcp::v4());
this->_acceptor->bind(*this->_endpoint);
this->_acceptor->listen();
this->_signals.add(SIGINT);
this->_signals.add(SIGTERM);
#if defined(SIGQUIT)
this->_signals_.add(SIGQUIT);
#endif // defined(SIGQUIT)
this->_signals.async_wait(boost::bind(&Server::shutdown, this));
this->queueAccept();
}
Server::~Server()
{
delete this->_acceptor;
delete this->_endpoint;
}
void Server::queueAccept()
{
this->_session.reset(new Session(*this));
_acceptor->async_accept(
this->_session->getSocket(),
boost::bind(
&Server::handleAccept,
this,
boost::asio::placeholders::error
)
);
}
void Server::handleAccept(const boost::system::error_code& error)
{
if (!error)
this->_session->start();
this->queueAccept();
}
boost::asio::io_service& Server::getIOService()
{
return this->_io_service;
}
void Server::shutdown()
{
this->_io_service.stop();
}
class Session:
public boost::enable_shared_from_this<Session>
{
public:
Session(Server& server);
~Session();
bool stopped() const;
virtual void start();
virtual boost::asio::ip::tcp::socket& getSocket();
virtual void disconnect();
/**
* Async read handler
*/
void handleRead(const boost::system::error_code& error, size_t bytesTransfered);
/**
* Async write handler
*/
void handleWrite(const boost::system::error_code& error);
/**
* Queues write action.
*/
void queueWrite();
/**
* Push a packet to be sent on queue end
*/
void pushPacket(protocols::SendPacket &packet);
void handleDeadlineAsyncWait(boost::asio::deadline_timer* deadline);
void handleDeadlineAsyncWaitKillConnection(boost::asio::deadline_timer* deadline);
private:
Server& _server;
boost::asio::ip::tcp::socket _socket;
boost::asio::io_service* _ioService;
boost::asio::io_service::strand _strand;
boost::asio::deadline_timer _input_deadline;
boost::asio::deadline_timer _non_empty_output_queue;
/**
* Queue that stores the packet to be sent.
*/
protocols::SendPacketQueue _writeQueue;
/**
* Referência do pacote que será atualizado.
*/
Protocol* _protocol;
/**
* Queues the async_read acction.
*/
virtual void queueRead();
virtual void _pushPacket(protocols::SendPacket &packet);
};
typedef boost::shared_ptr<Session> Session_SP;
#include "session.hpp"
Session::Session(Server& server):
_server(server), _socket(server.getIOService()), _protocol(NULL),
_ioService(&server.getIOService()), _strand(server.getIOService()),
_input_deadline(server.getIOService()),
_non_empty_output_queue(server.getIOService())
{
this->_input_deadline.expires_at(boost::posix_time::pos_infin);
this->_non_empty_output_queue.expires_at(boost::posix_time::pos_infin);
}
Session::~Session()
{
}
bool Session::stopped() const
{
return !_socket.is_open();
}
boost::asio::ip::tcp::socket& Session::getSocket()
{
return this->_socket;
}
void Session::disconnect()
{
this->_input_deadline.cancel();
this->_non_empty_output_queue.cancel();
try
{
this->getSocket().close();
LOG("Session::disconnect : close successful!");
}
catch (void* e)
{
// Never reached here!!
}
}
void Session::queueRead()
{
this->_input_deadline.expires_from_now(boost::posix_time::seconds(30));
boost::asio::async_read_until(
_socket,
_buffer,
"\x004", // Just a test
this->_strand.wrap(boost::bind(
&Session::handleRead,
this->shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
))
);
}
void Session::start()
{
this->queueRead();
this->_input_deadline.async_wait(
this->_strand.wrap(boost::bind(
&Session::handleDeadlineAsyncWait,
shared_from_this(),
&this->_input_deadline
))
);
this->queueWrite();
}
void Session::handleRead(const boost::system::error_code& error, size_t bytesTransfered)
{
if (this->stopped())
return;
if (!error)
{
// ... a lot of code here, but isn't important
}
else if (error != boost::asio::error::operation_aborted)
this->disconnect();
}
void Session::handleWrite(const boost::system::error_code& error)
{
if (this->stopped())
return;
if (!error)
{
this->_writeQueue.pop_front(); // Dequeue
this->queueWrite();
}
else
{
if (error != boost::asio::error::operation_aborted)
this->disconnect();
}
}
void Session::queueWrite()
{
if (this->stopped())
return;
if (this->_writeQueue.empty())
{
this->_non_empty_output_queue.expires_at(boost::posix_time::pos_infin);
this->_non_empty_output_queue.async_wait(
boost::bind(&Session::queueWrite, shared_from_this())
);
}
else
{
this->_input_deadline.expires_from_now(boost::posix_time::seconds(this->_server.getConfig().getServer().timeout));
boost::asio::async_write(
this->getSocket(),
boost::asio::buffer(
this->_writeQueue.front().getData(),
this->_writeQueue.front().getDataSize()
),
this->_strand.wrap(boost::bind(
&Session::handleWrite,
this,
boost::asio::placeholders::error
))
);
}
}
void Session::handleDeadlineAsyncWait(boost::asio::deadline_timer* deadline)
{
if (this->stopped())
return;
if (deadline->expires_at() <= boost::asio::deadline_timer::traits_type::now())
{
boost::system::error_code sdEc;
this->getSocket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, sdEc);
deadline->expires_from_now(boost::posix_time::seconds(15));
deadline->async_wait(
this->_strand.wrap(boost::bind(
&Session::handleDeadlineAsyncWaitKillConnection,
shared_from_this(),
deadline
))
);
}
else
{
deadline->async_wait(
this->_strand.wrap(boost::bind(
&Session::handleDeadlineAsyncWait,
shared_from_this(),
deadline
))
);
}
}
void Session::handleDeadlineAsyncWaitKillConnection(boost::asio::deadline_timer* deadline)
{
this->disconnect();
}
void Session::handleDeadlineAsyncWait(boost::asio::deadline_timer* deadline)
{
if (this->stopped())
return;
if (deadline->expires_at() <= boost::asio::deadline_timer::traits_type::now())
{
boost::system::error_code sdEc;
this->getSocket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, sdEc);
this->getSocket().cancel(); // <-- add this
}
else
{
deadline->async_wait(
this->_strand.wrap(boost::bind(
&Session::handleDeadlineAsyncWait,
shared_from_this(),
deadline
))
);
}
}
void Session::queueWrite()
{
if (this->stopped())
return;
if (!this->_writeQueue.empty())
{
boost::asio::async_write(
this->getSocket(),
boost::asio::buffer(
this->_writeQueue.front().getData(),
this->_writeQueue.front().getDataSize()
),
this->_strand.wrap(boost::bind(
&Session::handleWrite,
this,
boost::asio::placeholders::error
))
);
}
}