您的位置:首页 > 运维架构 > Linux

LinuxC/C++编程基础(16) boost异步socket处理

2012-12-04 15:51 519 查看
一.服务器端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库完全开发指南,罗剑锋 著

转载请注明出处:山水间博客:/article/2317649.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: