我正在学习boost / asio并编写电子书中的示例程序。 当然它不起作用;)
#include <boost/asio.hpp>
#include <iostream>
int main () {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver::query query("www.boost.org", "http");
boost::asio::ip::tcp::resolver::iterator destination = boost::asio::ip::tcp::resolver::resolve(query); // if i have "." before "resolve" as in books example compilers says i need primary-expresion.
boost::asio::ip::tcp::endpoint endpoint;
while ( destination != end ) {
endpoint = *destination++;
std::cout<<endpoint<<std::endl;
}
boost::asio::ip::tcp::socket socket(io_service);
socket.connect(endpoint);
return 0;
}
在“resolve”之前使用“::”编译输出:
/home/martins/C++/boost_asio_client/client.cpp|7|error: cannot call member function
‘boost::asio::ip::basic_resolver<InternetProtocol, ResolverService>::iterator
boost::asio::ip::basic_resolver<InternetProtocol,
ResolverService>::resolve(boost::asio::ip::basic_resolver<InternetProtocol,
ResolverService>::query&)
[with InternetProtocol = boost::asio::ip::tcp, ResolverService =
boost::asio::ip::resolver_service<boost::asio::ip::tcp>,
boost::asio::ip::basic_resolver<InternetProtocol, ResolverService>::iterator =
boost::asio::ip::basic_resolver_iterator<boost::asio::ip::tcp>,
boost::asio::ip::basic_resolver<InternetProtocol, ResolverService>::query =
boost::asio::ip::basic_resolver_query<boost::asio::ip::tcp>]’ without object|
任何人都可以告诉我如何正确解析地址?
答案 0 :(得分:6)
你需要一个resolver
对象。您的迭代器比较也不正确,您需要与标记值ip::tcp::resolver::iterator()
进行比较。
#include <boost/asio.hpp>
#include <iostream>
int main () {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver::query query("www.boost.org", "http");
boost::asio::ip::tcp::resolver resolver( io_service );
boost::asio::ip::tcp::resolver::iterator destination = resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint;
while ( destination != boost::asio::ip::tcp::resolver::iterator() ) {
endpoint = *destination++;
std::cout<<endpoint<<std::endl;
}
boost::asio::ip::tcp::socket socket(io_service);
socket.connect(endpoint);
return 0;
}
这是编译和运行代码的示例。
samm@macmini ~> g++ -lboost_system resolve.cc
samm@macmini ~> ./a.out
129.79.245.252:80
samm@macmini ~> echo $?
0
samm@macmini ~>
答案 1 :(得分:3)
resolve
不是静态成员函数,所以你需要创建一个解析器对象,然后在该对象上调用成员函数,比如(从内存中去,所以不要抱我这个在任何接近完美的地方):
int main () {
boost::asio::io_service io_service; // existing
boost::asio::ip::tcp::resolver::query query("www.boost.org", "http"); // existing
boost::asio::ip::tcp::resolver resolver(io_service); // added
// modified to use object defined above:
boost::asio::ip::tcp::resolver::iterator destination = resolver.resolve(query);