boost::asio异步模式的C/S客户端源码实现
生活随笔
收集整理的這篇文章主要介紹了
boost::asio异步模式的C/S客户端源码实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異步模式的服務器源碼
//g++ -g async_tcp_server.cpp -o async_tcp_server -lboost_system
//#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/system/error_code.hpp>using namespace std;
using namespace boost::asio;class server{private:io_service &ios;ip::tcp::acceptor acceptor;typedef boost::shared_ptr<ip::tcp::socket> 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 <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/shared_ptr.hpp>using namespace std;
using namespace boost::asio;class client{private:io_service& ios;ip::tcp::endpoint ep;typedef boost::shared_ptr<ip::tcp::socket> 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<vector<char> > str(new vector<char>(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<vector<char> > 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::asio异步模式的C/S客户端源码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: boost::asio中的C/S同步实例
- 下一篇: 使用boost解析域名服务