C++ Boost Asio去除Server中向量中的存储Session连接

问题描述 投票:0回答:1

我有两个综合问题

  1. 我不知道如何在 func read 中终止,如果它没有收到任何数据,则终止连接并通知服务器。
  2. 在完成接收数据后,从位于类服务器中的
    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();
            }
        });
}

我希望会话通知服务器它已完成接收数据并且服务器将其从向量中删除。

c++ boost boost-asio
1个回答
0
投票

我建议使用weak_ptr,因为你的会话已经在使用共享指针了。

这样您就可以避免紧密耦合:服务器只能检测过期的会话。

关于结束会话:事实上,您的异步操作捕获

self
会导致它保留下来。如果您不发布任何新的异步操作,则
Session
将隐式被破坏。

我将向您展示如何编辑示例,但它不是独立的。因此,请查看我的一些答案,做非常相似的事情:

您将能够找到更多搜索

expired
weak_ptr
remove_if

© www.soinside.com 2019 - 2024. All rights reserved.