boost::asio::io_service io_service ;还有要说明的是, boost::asio把通讯双方(server, client)都用endpoint的表示,所以endpoint中的address, port 分别封装了ip和端口。貌似resolver和endpoint不相干,于是乎出现tcp::resolver::iterator了,它是resolver的迭代器,其实就是endpoint的指针,那么就可以这样:
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query("localhost", "9000");
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);得到endpoint后就好说啦,endpoint.address().to_string()就能够返回string格式的ip地址,endpoint.port()返回端口。
boost::asio::ip::tcp::resolver::iterator end;
boost::system::error_code error = boost::asio::error::host_not_found;
boost::asio::ip::tcp::endpoint endpoint;
while (error && endpoint_iterator != end)
{
endpoint = *endpoint_iterator ;
socket.close();
socket.connect(endpoint, error);
endpoint_iterator++ ;
}
其实endpoint 完全可以自己构造,方法也是很简单的,tcp::endpoint(tcp::v4(), (unsigned short)9000) 这个是server端的用法,tcp::v4()直接返回自己的address,如果用于client那么需要设置server的ip ,实现如下:
boost::system::error_code error = boost::asio::error::host_not_found;这样不使用resolver也是可以的。
boost::asio::ip::address add;
add.from_string("127.0.0.1");
tcp::endpoint endpoint(add, short(9000));
socket.connect(endpoint, error);
还有更神奇的:
boost::asio::io_service ioservice ;这样有发现一个新的用途,通过resolver迭代可以得到多个节点endpoint,比如google 就有好几个ip。
boost::asio::io_service my_io_service ;
boost::asio::ip::tcp::resolver resolver(my_io_service);
boost::asio::ip::tcp::resolver::query query("www.google.com", "http");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end; // End marker.
while (iter != end)
{
boost::asio::ip::tcp::endpoint endpoint = *iter++;
std::cout << endpoint << std::endl;
}
上面这个例子的运行结果:
74.125.128.106:80
74.125.128.147:80
74.125.128.99:80
74.125.128.103:80
74.125.128.104:80
74.125.128.105:80