Chinaunix首页 | 论坛 | 博客
  • 博客访问: 87903
  • 博文数量: 19
  • 博客积分: 487
  • 博客等级: 下士
  • 技术积分: 205
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-18 15:57
文章分类

全部博文(19)

文章存档

2011年(19)

我的朋友

分类: 系统运维

2011-06-13 10:39:44

endin.pro
  1. message Endin
  2. {
  3.     required string ip = 1;
  4.     required int32 port = 2;
  5.     required int32 max_retry_times = 3;
  6. }
proxy.hpp
  1. #ifndef _CONNECTION_H
  2. #define _CONNECTION_H
  3. #include <iostream>
  4. #include <cstdio>
  5. #include <unistd.h>

  6. #include <boost/asio.hpp>
  7. #include <boost/asio/ip/tcp.hpp>
  8. #include <boost/asio/io_service.hpp>
  9. //#include <boost/bind.hpp>
  10. #include <boost/shared_ptr.hpp>
  11. #include <boost/thread.hpp>

  12. #include "endin.pro.pb.h"
  13. #define DELAYTIME 10
  14. #define RETRYTIME 10
  15. #define DEFAULT_SERVER_PORT 2048

  16. #define TRACE() do{cout << __FILE__ << " : " << __FUNCTION__ << " : " << __LINE__ << endl; }while (0)
  17. using namespace std;
  18. namespace PWRD{
  19.     namespace Net{
  20.         struct Header{ size_t length; };
  21. #define HEADERLEN sizeof(Header)

  22.         class Session{
  23.             protected:
  24.                 static int sid_;        
  25.             public:
  26.                 Session(){
  27.                 }
  28.                 virtual ~Session(){

  29.                 }

  30.                 int sid(){
  31.                     return ++sid_;
  32.                 }
  33.         };

  34.         int Session::sid_ = 0;

  35.         class PassiveSession: public Session{
  36.             public:    
  37.                 PassiveSession(boost::asio::io_service &_io_service):
  38.                     socket_(_io_service){

  39.                         cout << "Create a new PassiveSession" << endl;
  40.                     }
  41.                 boost::asio::ip::tcp::socket& socket(){
  42.                     return socket_;    
  43.                 }
  44.                 virtual ~PassiveSession(){
  45.                 }
  46.             private:
  47.                 boost::asio::ip::tcp::socket socket_;
  48.         };

  49.         class ActiveSession: public Session{
  50.             public:    
  51.                 ActiveSession(boost::asio::io_service &_io_service, string _ip, int _port, int _max_retry_times = RETRYTIME):
  52.                     socket_(_io_service),
  53.                     endpoint_(boost::asio::ip::address::from_string(_ip), _port),
  54.                     strand_(_io_service),
  55.                     max_retry_times_(_max_retry_times),
  56.                     connected_(false)

  57.             {
  58.                 cout << "Create a new ActiveSession" << endl;

  59.             }
  60.                 boost::asio::ip::tcp::socket& socket(){
  61.                     return socket_;    
  62.                 }

  63.                 void handle_connect(const boost::system::error_code &ec){
  64.                     if(!ec){
  65.                         cout << "Connected!" << endl;
  66.                         connected_ = true;    
  67.                     }    
  68.                 }    

  69.                 void start(){
  70.                     cout << "ActiveSession begin to establish a connection" << endl;
  71.                     run();
  72.                 }

  73.                 void run(){
  74.                     /*
  75.                     int retry = 0;
  76.                     while(!connected_ && retry < max_retry_times_){
  77.                         this->socket().async_connect(endpoint_,
  78.                                 strand_.wrap(    
  79.                                     bind(&ActiveSession::handle_connect, this,
  80.                                         boost::asio::placeholders::error
  81.                                      )));
  82.                         retry++;
  83.                         sleep(DELAYTIME);
  84.                     }
  85.                     */
  86.                     boost::system::error_code ec;
  87.                     this->socket().connect(endpoint_, ec);
  88.                     if(!ec){
  89.                         cout << "Connected!" << endl;
  90.                         connected_ = true;    
  91.                     }
  92.                     else{
  93.                         cout << "Error occur: errno=" << ec.value()
  94.                             << ", errmsg=" << ec.message()
  95.                             << endl;    
  96.                         TRACE();    
  97.                     }

  98.                 }


  99.                 bool connected(){
  100.                     return connected_;    
  101.                 }

  102.             private:
  103.                 boost::asio::ip::tcp::socket socket_;
  104.                 boost::asio::ip::tcp::endpoint endpoint_;
  105.                 boost::asio::io_service::strand strand_;
  106.                 int max_retry_times_;
  107.                 bool connected_;
  108.         };

  109.         class SessionPool{
  110.             public:
  111.                 typedef enum{ FORWARD, BACKWARD} DIRECTION;
  112.             public:
  113.                 typedef pair<Session *, Session *> SessionPair;
  114.                 void join(PassiveSession* ps, ActiveSession *as){
  115.                     SessionPair *session_pair = new SessionPair(ps, as);    
  116.                     session_map_[ps->sid()] = session_pair;
  117.                     cout << "Session: " << ps->sid() << " & " << as->sid() << " join the pool" << endl;
  118.                 }
  119.                 void leave(PassiveSession* ps){
  120.                     SessionPair *session_pair = session_map_[ps->sid()];
  121.                     if(NULL != session_pair){
  122.                         if(session_pair->first != NULL)
  123.                             delete session_pair->first;
  124.                         if(session_pair->second != NULL)
  125.                             delete session_pair->second;
  126.                         delete session_pair;
  127.                         session_map_[ps->sid()] = NULL;
  128.                         cout << "Session: " << session_pair->first->sid() << " & "
  129.                             << session_pair->second->sid() << " leave the pool" << endl;
  130.                     }
  131.                 }
  132.                 Session * session(Session *s, DIRECTION direction=FORWARD){
  133.                     if(FORWARD == direction){
  134.                         if(NULL != session_map_[s->sid()]){
  135.                             return session_map_[s->sid()]->second;    
  136.                         }
  137.                     }    
  138.                     else{
  139.                         SessionMap::iterator it = session_map_.begin();
  140.                         for(; it != session_map_.end(); it++){
  141.                             if(NULL != it->second){
  142.                                 if(s == it->second->second){
  143.                                     return it->second->first;    
  144.                                 }    
  145.                             }
  146.                         }
  147.                     }
  148.                 }
  149.             private:
  150.                 typedef map<int, SessionPair*> SessionMap;
  151.                 SessionMap session_map_;
  152.         };

  153.         class Proxy{
  154.             public:
  155.                 Proxy(boost::asio::io_service &_io_service, SessionPool &_session_pool, PassiveSession *_ps):
  156.                     io_service_(_io_service),
  157.                     session_pool_(_session_pool),
  158.                     ps_(_ps)
  159.             {
  160.                 cout << "Create a new Proxy......" << endl;
  161.                 *input_header_ = 0;
  162.                 *input_passive_ = 0;
  163.                 *input_active_ = 0;
  164.             }

  165.                 void start()
  166.                 {
  167.                     cout << "Proxy start ......" << endl;
  168.                     boost::asio::async_read(ps_->socket(),
  169.                             boost::asio::buffer(&input_header_, HEADERLEN),
  170.                             boost::bind(&Proxy::handle_read, this,
  171.                                 boost::asio::placeholders::error,
  172.                                 boost::asio::placeholders::bytes_transferred
  173.                                 ));    

  174.                 }

  175.                 void handle_read(const boost::system::error_code &_ec, size_t bytes_transferred){

  176.                     if(!_ec){
  177.                         cout << "Receive: " << bytes_transferred << " bytes" << endl;            
  178.                         Header * header = (Header*)input_header_;
  179.                         cout << "Receive header length: " << header->length << " bytes" << endl;            
  180.                         *buff_ = 0;
  181.                         boost::asio::async_read(ps_->socket(),
  182.                                 boost::asio::buffer(buff_, header->length),
  183.                                 boost::bind(&Proxy::handle_parse, this,
  184.                                     boost::asio::placeholders::error,
  185.                                     boost::asio::placeholders::bytes_transferred
  186.                                     ));    
  187.                     }
  188.                     else{
  189.                         cout << "Error occur: errno=" << _ec.value()
  190.                             << ", errmsg=" << _ec.message()
  191.                             << endl;    
  192.                         TRACE();
  193.                         stop();
  194.                     }
  195.                 }
  196.                 void handle_parse(const boost::system::error_code &_ec, size_t bytes_transferred){
  197.                     if(!_ec){
  198.                         //cout << "Receive " << bytes_transferred << " bytes" << endl;            
  199.                         Endin endin;
  200.                         if(!endin.ParseFromArray(buff_, bytes_transferred)){
  201.                             cout << "Parse endin faild" << endl;    
  202.                             return;
  203.                         }

  204.                         cout << "Endin: ip=" << endin.ip() << ", port=" << endin.port() << ", max_retry_times=" << endin.max_retry_times() << endl;

  205.                         string ip = endin.ip();
  206.                         int port = endin.port();
  207.                         int max_retry_times = endin.max_retry_times();
  208.                         as_ = new ActiveSession(io_service_,
  209.                                 ip, port, max_retry_times);
  210.                         as_->start();

  211.                         if(!as_->connected()){
  212.                             cout << "Can't connect to " << ip << ":" << port << endl;    
  213.                             return;
  214.                         }

  215.                         session_pool_.join(ps_, as_);
  216.                         handle_read_from_passive();    

  217.                     }
  218.                     else{
  219.                         cout << "Error occur: errno=" << _ec.value()
  220.                             << ", errmsg=" << _ec.message()
  221.                             << endl;    
  222.                         TRACE();
  223.                         stop();
  224.                     }
  225.                 }

  226.                 void handle_write(const boost::system::error_code &_ec, size_t bytes_transferred){

  227.                     if(!_ec){
  228.                         cout << "Receive " << bytes_transferred << " bytes" << endl;            
  229.                         handle_read_from_passive();
  230.                     }
  231.                     else{
  232.                         cout << "Error occur: errno=" << _ec.value()
  233.                             << ", errmsg=" << _ec.message()
  234.                             << endl;    
  235.                         TRACE();
  236.                         stop();
  237.                     }
  238.                 }


  239.                 void handle_read_from_passive(){
  240.                     ps_->socket().async_read_some(
  241.                             boost::asio::buffer(input_passive_),
  242.                             boost::bind(&Proxy::handle_write_to_active,
  243.                                 this,
  244.                                 boost::asio::placeholders::error,
  245.                                 boost::asio::placeholders::bytes_transferred
  246.                                 )
  247.                             );
  248.                 }

  249.                 void handle_read_from_active(const boost::system::error_code &_ec, size_t bytes_transferred){
  250.                     if(!_ec){
  251.                         cout << "Receive " << bytes_transferred << " bytes" << endl;            
  252.                     as_->socket().async_read_some(
  253.                             boost::asio::buffer(input_active_),
  254.                             boost::bind(&Proxy::handle_write_to_passive,
  255.                                 this,
  256.                                 boost::asio::placeholders::error,
  257.                                 boost::asio::placeholders::bytes_transferred
  258.                                 )
  259.                             );

  260.                     }
  261.                     else{
  262.                         cout << "Error occur: errno=" << _ec.value()
  263.                             << ", errmsg=" << _ec.message()
  264.                             << endl;    
  265.                         TRACE();
  266.                         stop();
  267.                     }
  268.                 }

  269.                 void handle_write_to_passive(const boost::system::error_code &_ec, size_t bytes_transferred){
  270.                     if(!_ec){
  271.                         input_active_[bytes_transferred] = 0;
  272.                         cout << "Recv--Contnet: " << input_active_ << endl;
  273.                         boost::asio::async_write(
  274.                                 ps_->socket(),
  275.                                 boost::asio::buffer(input_active_, bytes_transferred),
  276.                                 boost::bind(&Proxy::handle_write,
  277.                                     this,
  278.                                     boost::asio::placeholders::error,
  279.                                     boost::asio::placeholders::bytes_transferred
  280.                                     )
  281.                                 );    
  282.                     }    
  283.                     else{
  284.                         cout << "Error occur: errno=" << _ec.value()
  285.                             << ", errmsg=" << _ec.message()
  286.                             << endl;    
  287.                     }
  288.                 }

  289.                 void handle_write_to_active(const boost::system::error_code &_ec, size_t bytes_transferred){
  290.                     if(!_ec){
  291.                         input_passive_[bytes_transferred] = 0;
  292.                         cout << "Recv--Contnet: " << input_passive_ << endl;
  293.                         boost::asio::async_write(
  294.                                 as_->socket(),
  295.                                 boost::asio::buffer(input_passive_, bytes_transferred),
  296.                                 boost::bind(&Proxy::handle_read_from_active,
  297.                                     this,
  298.                                     boost::asio::placeholders::error,
  299.                                     boost::asio::placeholders::bytes_transferred
  300.                                     )
  301.                                 );    
  302.                     }    
  303.                     else{
  304.                         cout << "Error occur: errno=" << _ec.value()
  305.                             << ", errmsg=" << _ec.message()
  306.                             << endl;    

  307.                     }
  308.                 }


  309.                 void stop(){
  310.                     /*
  311.                     ps_->socket().close();
  312.                     as_->socket().close();
  313.                     session_pool_.leave(ps_);
  314.                     cout << "SessoinPair <" << ps_->sid() << "," << as_->sid() << "> stop" << endl;
  315.                     */
  316.                 }

  317.             private:
  318.                 boost::asio::io_service &io_service_;
  319.                 SessionPool &session_pool_;
  320.                 PassiveSession* ps_;
  321.                 ActiveSession *as_;
  322.                 char buff_[100];
  323.                 char input_header_[HEADERLEN];
  324.                 char input_passive_[BUFSIZ];
  325.                 char input_active_[BUFSIZ];

  326.         };

  327.         class Engine{
  328.             public:
  329.                 Engine(boost::asio::io_service &_io_service, int port = DEFAULT_SERVER_PORT):
  330.                     io_service_(_io_service),
  331.                     socket_(_io_service),
  332.                     strand_(_io_service),
  333.                     acceptor_(_io_service, boost::asio::ip::tcp::endpoint(
  334.                                 boost::asio::ip::tcp::v4(), port)){

  335.                         cout << "Engine start......" << endl;    
  336.                     }    

  337.                 void start(){
  338.                     cout << "ProxyServer is waiting for a new connector ......" << endl;
  339.                     PassiveSession *ps = new PassiveSession(io_service_);
  340.                     acceptor_.async_accept( ps->socket(),
  341.                             strand_.wrap(
  342.                                 boost::bind(&Engine::handle_accept,
  343.                                     this, _1, ps)
  344.                                 )    );
  345.                     //run();
  346.                 }

  347.                 void handle_accept(const boost::system::error_code &_ec, PassiveSession* _ps){
  348.                     if(!_ec){
  349.                         cout << "Accept a new socket......." << endl;
  350.                         Proxy *proxy = new Proxy(io_service_, session_pool_, _ps);
  351.                         proxy->start();
  352.                         proxy_list_.push_back(proxy);
  353.                         start();

  354.                     }    
  355.                     else{
  356.                         cout << "Error occur: errno=" << _ec.value()
  357.                             << ", errmsg=" << _ec.message()
  358.                             << endl;    
  359.                     }
  360.                 }

  361.                 void run(){
  362.                     while(true){
  363.                     }
  364.                 }

  365.                 virtual void stop(){
  366.                     socket_.close();    
  367.                     acceptor_.close();
  368.                 }

  369.                 virtual ~Engine(){
  370.                     cout << "Engine stop ......." << endl;
  371.                     vector<Proxy*>::iterator pit = proxy_list_.begin();    
  372.                     for(; pit != proxy_list_.end(); pit++){
  373.                         delete *pit;    
  374.                     }
  375.                 }
  376.             private:
  377.                 boost::asio::io_service &io_service_;
  378.                 boost::asio::ip::tcp::socket socket_;
  379.                 boost::asio::io_service::strand strand_;
  380.                 boost::asio::ip::tcp::acceptor acceptor_;
  381.                 SessionPool session_pool_;
  382.                 vector<Proxy*> proxy_list_;

  383.         };
  384.     }
  385. }
  386. #endif
proxy: main.cpp
  1. #include "proxy.hpp"
  2. using namespace PWRD::Net;

  3. int main(int argc, char* argv[]){
  4.     if(2 != argc){
  5.         cout << "Usage: " << argv[0] << " " << endl;    
  6.         return -1;
  7.     }
  8.     boost::asio::io_service io_service;
  9.     Engine *engine = new Engine(io_service, atoi(argv[1]));

  10.     engine->start();
  11.     /*
  12.     boost::shared_ptr<boost::thread> thread_ptr(
  13.             new boost::thread(
  14.                 boost::bind(&Engine::start, engine)
  15.                 )
  16.             );
  17.     thread_ptr.get()->join();
  18.             */

  19.     io_service.run();


  20.     return 1;
  21. }
client.hpp
  1. #ifndef _CLIENT_HPP
  2. #define _CLIENT_HPP
  3. #define DEFUALTRETRYTIMES 10

  4. #include <iostream>
  5. #include <boost/asio.hpp>
  6. #include <boost/bind.hpp>

  7. #include "endin.pro.pb.h"
  8. using namespace std;

  9. namespace PWRD{
  10.     namespace Net{
  11.         struct Header{ int length; };
  12. #define HEADERLEN sizeof(Header)
  13.         class Client{
  14.             public:        
  15.                 Client(boost::asio::io_service& _io_service, string _ip, int _port):
  16.                     socket_(_io_service),
  17.                     ip_(_ip), port_(_port),
  18.                     connected_(false)
  19.             {
  20.             }

  21.                 virtual ~Client(){

  22.                 }

  23.                 void start(){
  24.                     cout << "Client start ........." << endl;
  25.                     socket_.async_connect(
  26.                             boost::asio::ip::tcp::endpoint(
  27.                                 boost::asio::ip::address::from_string(ip_), port_),
  28.                             boost::bind(&Client::handle_connect, this, boost::asio::placeholders::error)
  29.                             );

  30.                 }

  31.                 size_t endin(){
  32.                     Endin endin;    
  33.                     endin.set_ip(ip_);
  34.                     endin.set_port(11100);
  35.                     endin.set_max_retry_times(DEFUALTRETRYTIMES);
  36.                     endin.SerializeToArray(buff, endin.ByteSize());
  37.                     return endin.ByteSize();
  38.                 }

  39.                 void stop(){
  40.                     socket_.close();    
  41.                 }
  42.             protected:
  43.                 virtual void handle_recv(){
  44.                     socket_.async_read_some(
  45.                             boost::asio::buffer(buff),
  46.                             boost::bind(&Client::handle_recv_data,
  47.                                 this,
  48.                                 boost::asio::placeholders::error,
  49.                                 boost::asio::placeholders::bytes_transferred
  50.                                 ));

  51.                 }

  52.                 virtual void handle_send(){
  53.                     boost::asio::async_write(socket_,
  54.                             boost::asio::buffer("Hello world", 11),            
  55.                             boost::bind(&Client::handle_write, this,
  56.                                 boost::asio::placeholders::error,
  57.                                 boost::asio::placeholders::bytes_transferred)
  58.                             );
  59.                     sleep(1);
  60.                 }

  61.                 virtual void handle_connect(const boost::system::error_code& _ec){
  62.                     if(_ec){
  63.                         cout << "Can't connect to the sever" << endl;    
  64.                     }    
  65.                     else{
  66.                         connected_ = true;    
  67.                         cout << "Connection established....." << endl;
  68.                         Header header;
  69.                         header.length = endin();
  70.                         boost::asio::async_write(socket_,
  71.                                 boost::asio::buffer(&header, HEADERLEN),            
  72.                                 boost::bind(&Client::handle_delivery, this,
  73.                                     boost::asio::placeholders::error,
  74.                                     boost::asio::placeholders::bytes_transferred)
  75.                                 );
  76.                         cout << "Endin has " << header.length << " bytes" << endl;
  77.                     }
  78.                 }

  79.                 virtual void handle_delivery(const boost::system::error_code& _ec, size_t bytes_transferred ){
  80.                     if(!_ec){
  81.                         cout << "Send to " << ip_ << ":" << port_ <<" "<< bytes_transferred << " bytes" << endl;        
  82.                         boost::asio::async_write(socket_,
  83.                                 boost::asio::buffer(buff, endin()),            
  84.                                 boost::bind(&Client::handle_write_header, this,
  85.                                     boost::asio::placeholders::error,
  86.                                     boost::asio::placeholders::bytes_transferred)
  87.                                 );
  88.                     }
  89.                     else{
  90.                         cout << "Error: errno=" << _ec.value()
  91.                             << ", errmsg=" << _ec.message() << endl;
  92.                         stop();    
  93.                     }

  94.                 }
  95.                 virtual void handle_write_header(const boost::system::error_code& _ec, size_t bytes_transferred){
  96.                     if(!_ec){
  97.                         cout << "Send to " << ip_ << ":" << port_ << " " << bytes_transferred << " bytes" << endl;        
  98.                         handle_send();
  99.                     }
  100.                     else{
  101.                         cout << "Error: errno=" << _ec.value()
  102.                             << ", errmsg=" << _ec.message() << endl;
  103.                         stop();    
  104.                     }

  105.                 }
  106.                 virtual void handle_write(const boost::system::error_code& _ec, size_t bytes_transferred){
  107.                     if(!_ec){
  108.                         cout << "Send to " << ip_ << ":" << port_ << " " << bytes_transferred << " bytes" << endl;        
  109.                         
  110.                         cout << "In Handle write............." << endl;
  111.                         handle_recv();
  112.                     }
  113.                     else{
  114.                         cout << "Error: errno=" << _ec.value()
  115.                             << ", errmsg=" << _ec.message() << endl;
  116.                         stop();    
  117.                     }

  118.                 }
  119.                 virtual void handle_recv_data(const boost::system::error_code& _ec, size_t bytes_transferred){
  120.                     if(!_ec){
  121.                         cout << "Recv from: " << ip_ << ":" << port_ << " " << bytes_transferred << " bytes" << endl;        
  122.                         buff[bytes_transferred] = 0;
  123.                         cout << "Content: " << buff << endl;
  124.                         handle_send();
  125.                     }
  126.                     else{
  127.                         cout << "Error: errno=" << _ec.value()
  128.                             << ", errmsg=" << _ec.message() << endl;
  129.                         stop();    
  130.                     }
  131.                 }
  132.             private:
  133.                 boost::asio::ip::tcp::socket socket_;
  134.                 char buff[BUFSIZ];
  135.                 string ip_;
  136.                 int port_;
  137.                 bool connected_;

  138.         };    
  139.     }
  140. }
  141. #endif
client: main.cpp
  1. #include "client.hpp"
  2. #include <boost/thread.hpp>
  3. #include <boost/shared_ptr.hpp>

  4. using namespace PWRD::Net;

  5. int main(int argc, char* argv[]){
  6.     if(3 != argc){
  7.         cout << "Usage: " << argv[0] << "
    " << endl;    
  8.         return -1;
  9.     }

  10.     boost::asio::io_service io_service;
  11.     string ip(argv[1]);
  12.     int port = atoi(argv[2]);
  13.     Client *client = new Client(io_service, ip, port);
  14.     client->start();
  15.     /*
  16.     boost::shared_ptr<boost::thread> thread(new boost::thread(
  17.                 boost::bind(&Client::start, client
  18.                     )));
  19.     

  20.     thread.get()->join();
  21.     */
  22.     io_service.run();


  23.     return 1;
  24. }

server.hpp

 

  1. #ifndef _SERVER_HPP
  2. #define _SERVER_HPP
  3. #define DEFAULT_SERVER_PORT 2048
  4. #include <iostream>
  5. #include <cstdio>
  6. #include <unistd.h>

  7. #include <boost/asio.hpp>
  8. #include <boost/asio/ip/tcp.hpp>
  9. #include <boost/asio/io_service.hpp>
  10. //#include <boost/bind.hpp>
  11. #include <boost/shared_ptr.hpp>
  12. #include <boost/thread.hpp>

  13. #include "endin.pro.pb.h"
  14. namespace PWRD{
  15.     namespace Net{
  16.         using namespace std;
  17.         struct Header{ size_t length; };
  18. #define HEADERLEN sizeof(Header)
  19.         class Session{
  20.             protected:
  21.                 static int sid_;        
  22.             public:
  23.                 Session(){
  24.                     ++sid_;
  25.                 }
  26.                 virtual ~Session(){

  27.                 }

  28.                 int sid(){
  29.                     return sid_;    
  30.                 }
  31.         };

  32.         int Session::sid_ = 0;

  33.         class PassiveSession: public Session{
  34.             public:    
  35.                 PassiveSession(boost::asio::io_service &_io_service):
  36.                     socket_(_io_service) {

  37.                         cout << "Create a new PassiveSession" << endl;
  38.                         *input_stream_ = 0;
  39.                         *output_stream_ = 0;
  40.                         *header_stream_ = 0;
  41.                     }
  42.                 boost::asio::ip::tcp::socket& socket(){
  43.                     return socket_;    
  44.                 }
  45.                 virtual ~PassiveSession(){
  46.                     cout << "~PassiveSession()" << endl;
  47.                 }

  48.                 virtual void start(){
  49.                     cout << "PassiveSession start to read......" << endl;    
  50.                     *input_stream_ = 0;
  51.                         socket_.async_read_some(
  52.                                 boost::asio::buffer(input_stream_),
  53.                                 boost::bind(&PassiveSession::handle_read_content, this,
  54.                                     boost::asio::placeholders::error,
  55.                                     boost::asio::placeholders::bytes_transferred
  56.                                     ));
  57.                 }
  58.                 virtual void run(){
  59.                     cout << "PassiveSession running ......" << endl;    
  60.                 }
  61.                 virtual void stop(){
  62.                     socket_.close();    
  63.                 }
  64.             protected:
  65.                 virtual void handle_read_content(const boost::system::error_code&_ec, size_t bytes_transferred){
  66.                     if(!_ec){
  67.                         input_stream_[bytes_transferred] = 0;
  68.                         cout << "Receive: " << bytes_transferred << " bytes" << endl
  69.                             << "Content: " << input_stream_ << endl;            
  70.                         boost::asio::async_write( socket_,
  71.                                 boost::asio::buffer("HELLO WORLD", 11),
  72.                                 boost::bind(&PassiveSession::handle_write,
  73.                                     this,
  74.                                     boost::asio::placeholders::error,
  75.                                     boost::asio::placeholders::bytes_transferred
  76.                                     )
  77.                                 );
  78.                         sleep(1);
  79.                     }
  80.                     else{
  81.                         cout << "Error occur: errno=" << _ec.value()
  82.                             << ", errmsg=" << _ec.message()
  83.                             << endl;    
  84.                         stop();
  85.                     }

  86.                 }
  87.                 virtual void handle_write(const boost::system::error_code& _ec, size_t bytes_transferred){
  88.                     if(!_ec){
  89.                         cout << "Write: " << bytes_transferred << " bytes" << endl;            
  90.                         socket_.async_read_some(
  91.                                 boost::asio::buffer(input_stream_),
  92.                                 boost::bind(&PassiveSession::handle_read_content, this,
  93.                                     boost::asio::placeholders::error,
  94.                                     boost::asio::placeholders::bytes_transferred
  95.                                     ));    
  96.                     }
  97.                     else{
  98.                         cout << "Error occur: errno=" << _ec.value()
  99.                             << ", errmsg=" << _ec.message()
  100.                             << endl;    
  101.                         stop();
  102.                     }

  103.                 }
  104.             private:
  105.                 boost::asio::ip::tcp::socket socket_;
  106.                 char header_stream_[BUFSIZ];
  107.                 char input_stream_[BUFSIZ];
  108.                 char output_stream_[BUFSIZ];

  109.         };

  110.         class Server{
  111.             public:
  112.                 Server(boost::asio::io_service& _io_service, int port = DEFAULT_SERVER_PORT):
  113.                     io_service_(_io_service),
  114.                     acceptor_(_io_service, boost::asio::ip::tcp::endpoint(
  115.                                 boost::asio::ip::tcp::v4(), port))
  116.             {

  117.             }
  118.                 virtual ~Server(){
  119.                 }
  120.                 virtual void start(){
  121.                     PassiveSession *ps = new PassiveSession(io_service_);    
  122.                     acceptor_.async_accept( ps->socket(),
  123.                             boost::bind(&Server::handle_accept,
  124.                                 this, _1, ps)
  125.                             );
  126.                 }
  127.             protected:
  128.                 virtual void handle_accept(const boost::system::error_code &_ec, PassiveSession* _ps){
  129.                     if(!_ec){
  130.                         cout << "Accept a new socket......." << endl;
  131.                         _ps->start();
  132.                         /*
  133.                         boost::shared_ptr<boost::thread> thread_ptr(new boost::thread(
  134.                                 boost::bind(&PassiveSession::start, _ps)
  135.                                     ));
  136.                         thread_ptr.get()->detach();
  137.                         */
  138.                         start();
  139.                     }    
  140.                     else{
  141.                         cout << "Error occur: errno=" << _ec.value()
  142.                             << ", errmsg=" << _ec.message()
  143.                             << endl;    
  144.                     }
  145.                 }
  146.             private:
  147.                 boost::asio::io_service &io_service_;
  148.                 boost::asio::ip::tcp::acceptor acceptor_;

  149.         };
  150.     }
  151. }
  152. #endif
  153.                 /*
  154.                 virtual void handle_read_header(const boost::system::error_code& _ec, size_t bytes_transferred){
  155.                     
  156.                     if(!_ec){
  157.                         cout << "Receive: " << bytes_transferred << " bytes" << endl;            
  158.                         Header * header = (Header*)header_stream_;
  159.                         *input_stream_ = 0;
  160.                         boost::asio::async_read(socket_,
  161.                                 boost::asio::buffer(input_stream_, header->length),
  162.                                 boost::bind(&PassiveSession::handle_read_body, this,
  163.                                     boost::asio::placeholders::error,
  164.                                     boost::asio::placeholders::bytes_transferred
  165.                                     ));    
  166.                     }
  167.                     else{
  168.                         cout << "Error occur: errno=" << _ec.value()
  169.                             << ", errmsg=" << _ec.message()
  170.                             << endl;    
  171.                         stop();
  172.                     }

  173.                 }
  174.                 virtual void handle_read_body(const boost::system::error_code& _ec, size_t bytes_transferred){
  175.                     if(!_ec){
  176.                         cout << "Receive: " << bytes_transferred << " bytes" << endl;            
  177.                         Endin endin;
  178.                         if(endin.ParseFromArray(input_stream_, bytes_transferred)){
  179.                             cout << "Endin: ip=" << endin.ip() << ", port=" << endin.port() << ", max_retry_times=" << endin.max_retry_times() << endl;
  180.                         }

  181.                         *input_stream_ = 0;
  182.                         socket_.async_read_some(
  183.                                 boost::asio::buffer(input_stream_),
  184.                                 boost::bind(&PassiveSession::handle_read_content, this,
  185.                                     boost::asio::placeholders::error,
  186.                                     boost::asio::placeholders::bytes_transferred
  187.                                     ));    
  188.                     }
  189.                     else{
  190.                         cout << "Error occur: errno=" << _ec.value()
  191.                             << ", errmsg=" << _ec.message()
  192.                             << endl;    
  193.                         stop();
  194.                     }

  195.                 }
  196.                 */
server: main.cpp
  1. #include "server.hpp"
  2. #include <boost/thread.hpp>
  3. #include <boost/shared_ptr.hpp>

  4. using namespace PWRD::Net;

  5. int main(int argc, char* argv[]){
  6.     if(2 != argc){ cout << "Usage: " << argv[0] << " " << endl;    
  7.         return -1;
  8.     }

  9.     boost::asio::io_service io_service;
  10.     int port = atoi(argv[1]);
  11.     Server *server = new Server(io_service, port);
  12.     server->start();
  13.     /*
  14.     boost::shared_ptr<boost::thread> thread(new boost::thread(
  15.                 boost::bind(&Server::start, server
  16.                     )));
  17.     

  18.     thread.get()->join();
  19.     */
  20.     io_service.run();


  21.     return 1;
  22. }
阅读(2282) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~