【问题标题】:boost::asio::ip::tcp::resolver::iterator Check if values are nullboost::asio::ip::tcp::resolver::iterator 检查值是否为空
【发布时间】:2017-03-21 21:35:32
【问题描述】:

我有一段代码在执行时会引发访问冲突。它是 boost::asio 的 async_connect 处理程序。

//------------------------------------------------------------------------------
void MyClient::OnConnect(const boost::system::error_code & errorCode, boost::asio::ip::tcp::resolver::iterator endpoint)
{
    if (errorCode || endpoint == boost::asio::ip::tcp::resolver::iterator())
    {
        // Error - An error occured while attempting to connect
        // Most likely these error codes correspond to https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx
        std::ostringstream msg;
        msg << "An error occured while attempting to connect to " << endpoint->host_name()
            << ". Error code: " << errorCode
            << ". Error Message: " << ErrorCodeToString(errorCode);

        LogError(msg.str().c_str(), __FUNCSIG__, __FILE__, __LINE__);
        return;
    }

    // We connected to an endpoint
    m_connectionState |= CONNECTED;

在调试器中,问题似乎在端点->host_name() 内部,因为它试图在 values_ 为空时获取 values_[0]。

这是一个常见的连接被拒绝场景。我认为处理程序获得了端点,以便它知道它试图连接到谁!在尝试调用迭代器的方法之前,是否可以对迭代器进行某种检查?

它似乎通过并仍然抛出访问冲突

if( endpoint != boost::asio::ip::tcp::resolver::iterator() )
{
    std::string blah = endpoint->host_name();
}

【问题讨论】:

    标签: c++ boost-asio


    【解决方案1】:

    您现在可能已经弄清楚了,但我会发布几行以防其他人发生。

    这个问题看起来和我遇到的类似。

    这将不起作用,并且会产生与您所描述的相似的结果。

     void establish_connection() {
          tcp::resolver resolver(get_asio_io_service());  // this is a problem      
          tcp::resolver::query q{server_name, "https"};
          resolver.async_resolve(q,
                                 [&](asio::error_code ec,
                                     tcp::resolver::iterator it) {
                                    this->handle_resolve(ec, it);
                                 });
       }
    

    其中建立连接()是对象中处理与服务器通信的方法。

    resolver 对象在建立连接() 退出后消失。你必须想办法让它坚持下去。网上各种demo都把它作为client对象的一个​​属性。

    请分享您解决此问题的经验。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多