我有两个综合问题
m_storageSession
向量中删除类 Session
std::vector<std::shared_ptr<Session>> m_StorageSession
;void Server::startAcceptNewConnectionAsync()
{
m_Acceptor.async_accept(
[this](boost::system::error_code aError_code, boost::asio::ip::tcp::socket aSocket)
{
if (!aError_code)
{
boost::asio::ip::tcp::endpoint endpoint = aSocket.remote_endpoint();
std::shared_ptr<SessionEchoBoost> newSession = std::make_shared<SessionEchoBoost>
(this, m_SessionID.GetFreeID(), endpoint.address().to_string(),
endpoint.port(), std::move(aSocket));
newSession->start();
m_StorageSession.push_back(newSession);
}
startAcceptNewConnectionAsync();
});
}
void Server::notificationAbautCloseConnectionSession(const size_t& theIdSession)
{
for (int i = 0; i < m_StorageSession.size(); ++i)
{
if (m_StorageSession[i]->getIdSession() == theIdSession)
{
m_SessionID.DeleteSession(m_StorageSession[i]->getIdSession());
m_StorageSession[i]->close();
break;
}
}
}
Session::~Session()
{
if (m_Owner)
{
m_Owner->notificationAbautCloseConnectionSession(m_IdSession); // Server*m_Owner
}
}
void Session::do_read()
{
auto self(shared_from_this());
m_Socket.async_read_some(boost::asio::buffer(m_FrameCommunicationDataIn.getBuforData() + m_FrameCommunicationDataIn.getIndexSaveDataInBuffor(), m_FrameCommunicationDataIn.getSizeBufforData()),
[this, self](boost::system::error_code ec, std::size_t length)
{
if (!ec)
{
if (length != 0)
{
m_FrameCommunicationDataIn.setAmauntCopyDataIn(length);
newDataFromSession();
}
else
{
this->~Session();
}
do_read();
}
});
}
我希望会话通知服务器它已完成接收数据并且服务器将其从向量中删除。
我建议使用weak_ptr,因为你的会话已经在使用共享指针了。
这样您就可以避免紧密耦合:服务器只能检测过期的会话。
关于结束会话:事实上,您的异步操作捕获
self
会导致它保留下来。如果您不发布任何新的异步操作,则 Session
将隐式被破坏。
我将向您展示如何编辑示例,但它不是独立的。因此,请查看我的一些答案,做非常相似的事情:
您将能够找到更多搜索
expired
weak_ptr
remove_if
等