1.socket类是TCP通信的基本类,调用成员函数connect()可以连接到一个指定的通信端点,连接成功后用local_endpoint()和remote_endpoint()获得连接两端的端点信,用read_some()和write_some()阻塞读写数据,当操作完成后使用close()函数关闭socket。如果不关闭socket,那么在socket析构时也会自动调用close()关闭。
2.acceptor类对应socketAPI的accept()函数功能,它用于服务器端,在指定的端口号接受连接,必须配合socket类才能完成通信。
3.resolver类对象socketAPI的getaddrinfo()系列函数,用于客户端解析网址获得可用的IP地址,解析得到的IP地址可以使用socket对象连接。
服务器端:
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp> int main()
{
try
{
std::cout << "server start..." << std::endl;
boost::asio::io_service ios;
boost::asio::ip::tcp::acceptor acceptor(ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6688)); // 接受6688端口
std::cout << acceptor.local_endpoint().address() << std::endl;
while (true) // 循环执行服务
{
boost::asio::ip::tcp::socket sock(ios); // socket对象
acceptor.accept(sock); // 阻塞等待socket连接
std::cout << "client:";
std::cout << sock.remote_endpoint().address() << std::endl;
sock.write_some(boost::asio::buffer("hello client...")); // 发送数据 }
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
客户端:
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <vector> class a_timer
{
private:
int count, count_max;
boost::function<void()> f; // 无参无返回的可调用用
boost::asio::deadline_timer t; // 定时器
public:
template<typename F>
a_timer(boost::asio::io_service &ios, int x, F func) :
f(func), count_max(x), count(0), t(ios, boost::posix_time::millisec(500))
{
t.async_wait(boost::bind(&a_timer::call_func, this, _1)); // 注册回调函数
}
void call_func(const boost::system::error_code &e)
{
if (count > count_max)
{
return;
}
++count;
f();
t.expires_at(t.expires_at() + boost::posix_time::millisec(500));
t.async_wait(boost::bind(&a_timer::call_func, this, _1)); // 再次启动定时器
}
}; void client(boost::asio::io_service &ios)
{
try
{
std::cout << "client start..." << std::endl;
boost::asio::ip::tcp::socket sock(ios);
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 6688);
sock.connect(ep); // socket连接到端点
std::vector<char> str(100, 0);
sock.read_some(boost::asio::buffer(str)); // 接收数据
std::cout << "recive from " << sock.remote_endpoint().address() << ": ";
std::cout << &str[0] << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
int main()
{
boost::asio::io_service ios;
a_timer t(ios, 5, boost::bind(client, boost::ref(ios)));
ios.run();
return 0;
}