Fixed a few problems, added a debugging configuration variable
[theodwalha.git] / source / server.cpp
blob9d18c730acd51f8a2fc226770a9a5cf0be31d943
1 #include <boost/bind.hpp>
2 #include <iostream>
3 #include <theodwalha/server.hpp>
4 #include <theodwalha/configuration.hpp>
6 http_server::http_server(boost::asio::io_service & io_service, std::string const & temporary_file_directory):
7 running(false),
8 io_service(io_service),
9 acceptor(io_service),
10 file_manager(temporary_file_directory)
14 bool http_server::launch_server(ushort new_port)
16 if(running)
18 std::cout << "Server is already running" << std::endl;
19 return false;
22 if(!file_manager.initialise())
24 std::cout << "Failed to initialise temporary file manager" << std::endl;
25 return false;
28 if(!modules.load_modules(module_directory))
29 return false;
31 boost::system::error_code error;
32 boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), new_port);
33 acceptor.open(endpoint.protocol());
34 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
35 acceptor.bind(endpoint, error);
36 acceptor.listen(backlog);
37 if(!error)
39 running = true;
40 port = new_port;
41 accept();
42 return true;
44 else
46 std::cout << "Failed to bind acceptor on port " << new_port << ": " << error << std::endl;
47 return false;
51 void http_server::accept()
53 http_server_client * new_client = new http_server_client(io_service, file_manager, modules);
54 acceptor.async_accept(new_client->socket, boost::bind(&http_server::accept_event, this, boost::asio::placeholders::error, new_client));
57 void http_server::accept_event(boost::system::error_code const & error, http_server_client * new_client)
59 if(!error)
61 boost::asio::ip::tcp::endpoint endpoint = new_client->socket.remote_endpoint();
62 if(debugging)
63 std::cout << "New connection from " << endpoint.address().to_string() << ":" << endpoint.port() << std::endl;
64 new_client->start();
65 accept();
67 else
69 std::cout << "Accept error: " << error << std::endl;
70 delete new_client;