summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVegard Storheil Eriksen <zyp@jvnv.net>2010-11-01 17:10:45 +0100
committerVegard Storheil Eriksen <zyp@jvnv.net>2010-11-01 17:10:45 +0100
commit36968bf3f13378c5d5fbb9882401a16a627aeaab (patch)
treec918f7ac9708895808cdb009c0e588b456c5204c
parent8838165554a818882d0412a2b0ae8611e0b34b0f (diff)
Boost.Asio demo.
-rw-r--r--server/SConstruct2
-rw-r--r--server/main.cpp70
2 files changed, 71 insertions, 1 deletions
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 <iostream>
+#include <boost/bind.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/enable_shared_from_this.hpp>
+#include <boost/asio.hpp>
+using boost::asio::ip::tcp;
-int main() {
+class tcp_connection : public boost::enable_shared_from_this<tcp_connection> {
+ public:
+ typedef boost::shared_ptr<tcp_connection> 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;
+ }
}