gpt4 book ai didi

sockets - boost::asio::async_resolve 问题

转载 作者:行者123 更新时间:2023-12-02 12:03:37 43 4
gpt4 key购买 nike

我正在构造一个使用 boost::asio 的 Socket 类。首先,我创建了一个 connect 方法,该方法获取主机和端口并将其解析为 IP 地址。这很有效,所以我决定研究一下async_resolve。但是,我的回调总是收到错误代码 995(使用与同步工作时相同的目标主机/端口)。

代码:

启动解析的函数:

  // resolve a host asynchronously
template<typename ResolveHandler>
void resolveHost(const String& _host, Port _port, ResolveHandler _handler) const
{
boost::asio::ip::tcp::endpoint ret;
boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port));
boost::asio::ip::tcp::resolver r(m_IOService);
r.async_resolve(query, _handler);
}; // eo resolveHost

调用该函数的代码:

  void Socket::connect(const String& _host, Port _port)
{
// Anon function for resolution of the host-name and asynchronous calling of the above
auto anonResolve = [this](const boost::system::error_code& _errorCode,
boost::asio::ip::tcp::resolver_iterator _epIt)
{
// raise event
onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode));

// perform connect, calling back to anonymous function
if(!_errorCode)
connect(*_epIt);
};

// Resolve the host calling back to anonymous function
Root::instance().resolveHost(_host, _port, anonResolve);

}; // eo connect

error_codemessage() 函数是:

The I/O operation has been aborted because of either a thread exit or an application request

我的 main.cpp 看起来像这样:

int _tmain(int argc, _TCHAR* argv[])
{
morse::Root root;
TextSocket s;
s.connect("somehost.com", 1234);
while(true)
{
root.performIO(); // calls io_service::run_one()
}
return 0;
}

提前致谢!

最佳答案

您的resolver对象超出了范围,请将其移至Socket类的成员,并使resolveHost成为一个方法而不是免费的功能。

发生这种情况是因为 boost::asio::ip::tcp::resolvera typedef of一个basic_resolverwhich inherits来自basic_io_object。当解析器超出范围时,~basic_io_object() destroys handler can be posted 之前的底层解析器服务.

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

关于sockets - boost::asio::async_resolve 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4636608/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com