Advertisement
Guest User

Untitled

a guest
May 31st, 2011
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #ifndef _SERVER_H_
  2. #define _SERVER_H_
  3.  
  4. #include "Connection.h"
  5. #include "ConnectionFactory.h"
  6.  
  7. class Server
  8. {
  9. public:
  10.   Server(boost::asio::io_service& io_service , std::string ip,short port,std::shared_ptr<ConnectionFactory> factory);
  11.   ~Server();   
  12. private:
  13.   void start_accept();
  14.   void handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error);
  15.  
  16.   std::shared_ptr<ConnectionFactory> m_factory;
  17.   boost::asio::io_service io_service;
  18.   boost::asio::ip::tcp::acceptor acceptor_;
  19. };
  20.  
  21. #endif
  22.  
  23. #include "Server.h"
  24.  
  25.  
  26. Server::Server(boost::asio::io_service& io_service,std::string ip,short port,std::shared_ptr<ConnectionFactory> factory)
  27.     : acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ip.data()), port)){
  28.  
  29.         m_factory = factory;
  30.         start_accept();
  31.  
  32.         std::cout<<"Socket accepting connections..."<<std::endl;
  33. }
  34.  
  35. Server::~Server()
  36. {
  37. }
  38.  
  39.  
  40. void Server::start_accept(){
  41.    
  42.     std::shared_ptr<Connection> conn = m_factory->create(this->io_service);
  43.  
  44.     acceptor_.async_accept(conn->socket(),
  45.         boost::bind(&Server::handle_accept, this,conn,
  46.           boost::asio::placeholders::error));
  47.    
  48. }
  49.  
  50.  
  51. void Server::handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error){
  52.  
  53.     if (!error)
  54.     {
  55.         std::cout<<"on connected"<<std::endl;
  56.         conn->OnConnected();
  57.         start_accept();
  58.     }
  59.     else{
  60.         conn->Disconnect();
  61.     }
  62.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement