From 36968bf3f13378c5d5fbb9882401a16a627aeaab Mon Sep 17 00:00:00 2001 From: Vegard Storheil Eriksen Date: Mon, 1 Nov 2010 17:10:45 +0100 Subject: Boost.Asio demo. --- server/SConstruct | 2 ++ server/main.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/server/SConstruct b/server/SConstruct index b8329cd..d1def28 100644 --- a/server/SConstruct +++ b/server/SConstruct @@ -7,6 +7,8 @@ env = Environment( AddOption('--release', action = 'store_true') AddOption('--profiling', action = 'store_true') +env.Append(LIBS = ['boost_system', 'pthread']) + if not GetOption('release'): env.Append(CPPFLAGS = ['-Wall', '-g']) diff --git a/server/main.cpp b/server/main.cpp index 443bd82..9341623 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -1,5 +1,73 @@ +#include +#include +#include +#include +#include +using boost::asio::ip::tcp; -int main() { +class tcp_connection : public boost::enable_shared_from_this { + public: + typedef boost::shared_ptr pointer; + + static pointer create(boost::asio::io_service& io_service) { + return pointer(new tcp_connection(io_service)); + } + + tcp::socket& socket() { + return socket_; + } + + void start() { + boost::asio::async_write(socket_, boost::asio::buffer("Hei!\n"), + boost::bind(&tcp_connection::handle_write, shared_from_this())); + } + private: + tcp::socket socket_; + + tcp_connection(boost::asio::io_service& io_service) : socket_(io_service) { + } + + void handle_write() { + } +}; + +class tcp_server { + public: + tcp_server(boost::asio::io_service& io_service) + : acceptor_(io_service, tcp::endpoint(tcp::v4(), 12345)) { + start_accept(); + } + + private: + tcp::acceptor acceptor_; + + void start_accept() { + tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.io_service()); + + acceptor_.async_accept(new_connection->socket(), boost::bind(&tcp_server::handle_accept, this, new_connection, boost::asio::placeholders::error)); + } + + void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { + if(!error) { + new_connection->start(); + start_accept(); + } + } +}; + +int main() { + try { + boost::asio::io_service io_service; + + tcp_server server(io_service); + + std::cout << "Listening to port 12345" << std::endl; + + io_service.run(); + + } catch(std::exception& e) { + std::cerr << "Exception caught: " << e.what() << std::endl; + } } -- cgit v1.2.3