Fimbulwinter Project  Pre-Alpha
An Ragnarok Online Emulator
Common/tcp_server.hpp
00001 /*==================================================================*
00002 *     ___ _           _           _          _       _                          *
00003 *    / __(_)_ __ ___ | |__  _   _| |_      _(_)_ __ | |_ ___ _ __       *
00004 *   / _\ | | '_ ` _ \| '_ \| | | | \ \ /\ / / | '_ \| __/ _ \ '__|      *
00005 *  / /   | | | | | | | |_) | |_| | |\ V  V /| | | | | ||  __/ |         *
00006 *  \/    |_|_| |_| |_|_.__/ \__,_|_| \_/\_/ |_|_| |_|\__\___|_|         *
00007 *                                                                                                                                       *
00008 * ------------------------------------------------------------------*
00009 *                                                        Emulator                                       *
00010 * ------------------------------------------------------------------*
00011 *                     Licenced under GNU GPL v3                     *
00012 * ----------------------------------------------------------------- *
00013 *                          Socket Modules                               *
00014 * ==================================================================*/
00015 
00016 #pragma once
00017 
00018 #include <boost/bind.hpp>
00019 #include <boost/asio.hpp>
00020 #include <boost/asio/ip/tcp.hpp>
00021 
00022 #include <tcp_connection.hpp>
00023 
00024 using namespace boost::asio::ip;
00025 
00026 class tcp_server
00027 {
00028 private:
00029         tcp::acceptor acceptor_;
00030         tcp_connection::parse default_parser_;
00031 
00032 public:
00033         tcp_server(boost::asio::io_service &io_service, address &addr, unsigned short port)
00034                 : acceptor_(io_service, tcp::endpoint(addr, port))
00035         {
00036                 default_parser_ = 0;
00037 
00038                 start_accept();
00039         }
00040 
00041         void start_accept()
00042         {
00043                 tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_io_service());
00044 
00045                 acceptor_.async_accept(new_connection->socket(),
00046                         boost::bind(&tcp_server::handle_accept, this, new_connection,
00047                         boost::asio::placeholders::error));
00048         }
00049 
00050         void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error)
00051         {
00052                 if (!error)
00053                 {
00054                         new_connection->set_parser(default_parser_);
00055                         new_connection->start();
00056                 }
00057 
00058                 start_accept();
00059         }
00060 
00061         void set_default_parser(tcp_connection::parse p)
00062         {
00063                 default_parser_ = p;
00064         }
00065 };
 All Classes Functions