服务器端:
#include <boost/thread.hpp> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> class Server { private: boost::asio::io_service &ios; boost::asio::ip::tcp::acceptor acceptor; typedef boost::shared_ptr<boost::asio::ip::tcp::socket> sock_pt; public: Server(boost::asio::io_service &io) : ios(io), acceptor(ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6688)) { start(); } void start() { sock_pt sock(new boost::asio::ip::tcp::socket(ios)); // 智能指针 acceptor.async_accept(*sock, boost::bind(&Server::accept_handler, this, _1, sock)); // 异步监听服务 } void accept_handler(const boost::system::error_code &e, sock_pt sock) { if (e) // 检测错误码 { return; } std::cout << "client: "; std::cout << sock->remote_endpoint().address() << std::endl; sock->async_write_some(boost::asio::buffer("hello client..."), boost::bind(&Server::write_hander, this, _1)); start(); // 再次启动异步监听 } void write_hander(const boost::system::error_code &e) { std::cout << "send message complete." << std::endl; } }; int main() { try { std::cout << "server start..." << std::endl; boost::asio::io_service ios; Server server(ios); ios.run(); // 启动异步调用事件处理循环 } 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 Client { private: boost::asio::io_service &ios; boost::asio::ip::tcp::endpoint ep; typedef boost::shared_ptr<boost::asio::ip::tcp::socket> sock_pt; public: Client(boost::asio::io_service &io) :ios(io), ep(boost::asio::ip::address::from_string("127.0.0.1"), 6688) { start(); // 启动异步连接 } void start() { sock_pt sock(new boost::asio::ip::tcp::socket(ios)); sock->async_connect(ep, boost::bind(&Client::conn_hander, this, _1, sock)); // 异步连接 } void conn_hander(const boost::system::error_code &e, sock_pt sock) { if (e) { return; } std::cout << "recive from " << sock->remote_endpoint().address() << ": "; boost::shared_ptr<std::vector<char> > str(new std::vector<char>(100, 0)); sock->async_read_some(boost::asio::buffer(*str), boost::bind(&Client::read_hander, this, _1, str)); // 异步读取数据 start(); // 再次启动异步连接 } void read_hander(const boost::system::error_code &e, boost::shared_ptr<std::vector<char> > str) { if (e) { return; } std::cout << &(*str)[0] << std::endl; } }; int main() { try { std::cout << "client start..." << std::endl; boost::asio::io_service ios; Client client(ios); ios.run(); } catch (std::exception &e) { std::cout << e.what() << std::endl; } return 0; }