boost :: asio-关闭服务器然后再备份后,服务器将不会重新连接到客户端

时间:2018-10-01 18:34:04

标签: boost tcp asio

如果我的客户端先运行,然后启动服务器,则服务器将连接。但是,如果我关闭服务器(客户端仍在运行)并重新启动服务器,它将无法重新连接到客户端。当服务器关闭时,我取消,关闭并关闭套接字。但是,当服务器重新启动时,Connect方法不会再次启动。我无权访问服务器代码。我不确定在哪一层检测到连接请求。

代码段: RadaClient继承客户端...

RadaClient的构造函数:

RadaClient::RadaClient(const std::string& aHostIp,
                           const int& aHostPort) :
        mIoServiceWorkPtr(std::unique_ptr<boost::asio::io_service::work>(new boost::asio::io_service::work(mIoService))),
        mIoThreadPtr(std::unique_ptr<boost::thread>(new boost::thread(boost::bind(&boost::asio::io_service::run, &mIoService)))),
Client(aHostIp, aHostPort, mIoService)
{
      std::cout << "host ip " 
                << aHostIp 
                << " host port " 
                << aHostPort << std::endl;
}

class Client
{
public:    
    bool Connect()
    {
        _mConnected = false;
        while (!_mConnected)
        {
            try
            {
                tcp::resolver resolver(_mSocket.get_io_service());
                tcp::resolver::query query(tcp::v4(), _mHost, 
                boost::lexical_cast<std::string> (_mPort));
                tcp::resolver::iterator iterator resolver.resolve(query);
                _mSocket.connect(*iterator);
                _mConnected = true;
            }
            catch (std::exception& e)
            {
                std::cout << "Caught exception \"" << e.what() << "\"\n";
                // printf("connect attempt failed\n");
                _mConnected = false;
            }
        }

        std::cerr << "TCP Client Successfully Connected... " << std::endl;

        _mMessageHandleThreadPtr.reset(new 
        boost::thread(boost::bind(&Client::_MessageHandleThread, this)));
        _mReadMessageThreadPtr.reset(new boost::thread(boost::bind(&Client::_ReadMessageThread, this)));
        return true;
    }

    void Disconnect()
    {
        std::cerr << "TCP Client";
        if (_mConnected)
        {
            _mConnected = false;        
            try
            {
                _mSocket.cancel();
                _mSocket.shutdown(_mSocket.shutdown_both);
                _mSocket.close();
            }
            catch (std::exception& e)
            {
                std::cerr << "Exception Disconnect(): " 
                          << e.what() << "\n";
            }
        }
        std::cerr << " Disconnected" << std::endl;
    }

0 个答案:

没有答案