一.伺服器端server.cpp的實現,如下:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost;
using namespace boost::asio;
class server{
private:
io_service& ios;
ip::tcp::acceptor acceptor;
typedef shared_ptr<ip::tcp::socket> sock_pt;
public:
server(io_service& io):ios(io)
,acceptor(ios,ip::tcp::endpoint(ip::tcp::v4(),9999))
{
start();
}
void start(){
sock_pt sock(new ip::tcp::socket(ios));
acceptor.async_accept(*sock,bind(&server::accept_handler,this,placeholders::error,sock));
}
void accept_handler(const system::error_code& ec,sock_pt sock){
if(ec){
return;
}
std::cout<<"client: ";
std::cout<<sock->remote_endpoint().address()<<std::endl;
sock->async_write_some(buffer("hello asio"),bind(&server::write_handler,this,placeholders::error));
start();
}
void write_handler(const system::error_code& e){
std::cout<<"send message complete."<<std::endl;
}
};
int main(int argc,char** argv){
try{
std::cout<<"server start."<<std::endl;
io_service ios;
server serv(ios);
ios.run();
}catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
return 0;
}
二.用戶端client.cpp的實現,如下:
#include <iostream>
#include <vector>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;
class client{
private:
io_service& ios;
ip::tcp::endpoint ep;
typedef shared_ptr<ip::tcp::socket> sock_pt;
public:
client(io_service& io):ios(io)
,ep(ip::address::from_string("127.0.0.1"),9999)
{
start();
}
void start(){
sock_pt sock(new ip::tcp::socket(ios));
sock->async_connect(ep,bind(&client::conn_handler,this,placeholders::error,sock));
}
void conn_handler(const system::error_code& ec,sock_pt sock){
if(ec){
return;
}
std::cout<<"receive from "<<sock->remote_endpoint().address()<<std::endl;
shared_ptr<std::vector<char> > str(new std::vector<char>(100,0));
sock->async_read_some(buffer(*str),bind(&client::read_handler,this,placeholders::error,str));
start();
}
void read_handler(const system::error_code& ec,shared_ptr<std::vector<char> >str){
if(ec){
return;
}
std::cout<<&(*str)[0]<<std::endl;
}
};
int main(int argc,char** argv){
try{
std::cout<<"client start."<<std::endl;
io_service ios;
client cli(ios);
ios.run();
}catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
return 0;
}
三.運行結果,如下:
伺服器端:
用戶端:
參考文獻:boost庫完全開發指南,羅劍鋒 著
轉載請註明出處:山水間部落格:http://blog.csdn.net/linyanwen99/article/details/8256266