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

时间:2022-09-08 22:34:33

异步模式的服务器源码

//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 frequency
deadline_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;
}
}

运行效果截图

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

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

参考文献

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