#ifndef _SERVER_H_
#define _SERVER_H_
#include "Connection.h"
#include "ConnectionFactory.h"
class Server
{
public:
Server(boost::asio::io_service& io_service , std::string ip,short port,std::shared_ptr<ConnectionFactory> factory);
~Server();
private:
void start_accept();
void handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error);
std::shared_ptr<ConnectionFactory> m_factory;
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor_;
};
#endif
#include "Server.h"
Server::Server(boost::asio::io_service& io_service,std::string ip,short port,std::shared_ptr<ConnectionFactory> factory)
: acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ip.data()), port)){
m_factory = factory;
start_accept();
std::cout<<"Socket accepting connections..."<<std::endl;
}
Server::~Server()
{
}
void Server::start_accept(){
std::shared_ptr<Connection> conn = m_factory->create(this->io_service);
acceptor_.async_accept(conn->socket(),
boost::bind(&Server::handle_accept, this,conn,
boost::asio::placeholders::error));
}
void Server::handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error){
if (!error)
{
std::cout<<"on connected"<<std::endl;
conn->OnConnected();
start_accept();
}
else{
conn->Disconnect();
}
}