首页 > boost::asio异步模式的C/S客户端源码实现

boost::asio异步模式的C/S客户端源码实现

异步模式的服务器源码

//g++ -g async_tcp_server.cpp -o async_tcp_server -lboost_system
//#include 
#include 
#include 
#include 
#include using namespace std;
using namespace boost::asio;class server{private:io_service &ios;ip::tcp::acceptor acceptor;typedef boost::shared_ptr sock_ptr;public:server(io_service& io): ios(io),acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688)){ start(); }void start(){sock_ptr sock(new ip::tcp::socket(ios));acceptor.async_accept(*sock, bind(&server::accept_handler, this, placeholders::error, sock));}void accept_handler(const boost::system::error_code& ec, sock_ptr sock){if(ec) return;cout << "client: ";cout << sock->remote_endpoint().address() << endl;sock->async_write_some(buffer("hello asio"), bind(&server::write_handler, this, placeholders::error));start(); //retry to accept the next quest ......}void write_handler(const boost::system::error_code&){cout << "send msg complete." << endl;}
};int main(){try{cout << "async tcp server start ......" << endl;io_service ios;server serv(ios);ios.run();}catch(std::exception& e){cout << e.what() << endl;}
}

异步模式的客户端源码

//g++ -g async_tcp_client.cpp -o async_tcp_client -lboost_system -lboost_date_time
//#include 
#include 
#include 
#include 
#include using namespace std;
using namespace boost::asio;class client{private:io_service& ios;ip::tcp::endpoint ep;typedef boost::shared_ptr sock_ptr;public:client(io_service& io): ios(io),ep(ip::address::from_string("127.0.0.1"), 6688){start();}void start(){sock_ptr sock(new ip::tcp::socket(ios));sock->async_connect(ep, bind(&client::conn_handler, this, placeholders::error, sock));}void conn_handler(const boost::system::error_code& ec, sock_ptr sock){if(ec)  return;cout << "receive from " << sock->remote_endpoint().address() << endl;boost::shared_ptr > str(new vector(100, 0));sock->async_read_some(buffer(*str), bind(&client::read_handler, this, placeholders::error, str));//sync timer block to control the client connection frequencydeadline_timer t(ios, boost::posix_time::seconds(5));t.wait();start(); //retry to connect in the next time}void read_handler(const boost::system::error_code& ec, boost::shared_ptr > str){if(ec) return;cout << &(*str)[0] << endl;}
};int main()
{try{cout << "client start ......" << endl;io_service ios;client cl(ios);ios.run();return 0;}catch(exception& e){cout << e.what() << endl;}
}

运行效果截图





参考文献

[1].罗剑锋, Boost程序库完全开发指南---深入C++"准"标准库

更多相关:

  • 近来狂热地研究boost的开发技术,现将读书笔记整理如下: 需要说明的是, 本博该专题下面关于boost的源码是采用boost1.55版本, 运行在Ubuntu 14.04 64bit下面, 使用apt包安装(非源码编译安装), 后续不再做说明. 同步socket类型的服务器源码实现: //g++ -g sync_tcp_s...

  • 通过实验取证:TCP三次握手的过程理解TCP/IP协议的工作原理多年来TCP/IP协议一直被公众称呼为“一个协议”,事实上它是一组协议的集合,IP工作在OSI七层模型的网络层,提供网络传输,但是并不提供其可靠性传输控制。而TCP工作在OSI七层模型的传输层,并提供其可靠性传输控制。那么首先需要说明的是:“什么是可靠性传输控制?”所谓可...