d90ec9116dcf9ed5e1fa5d75e12063c3a9c4072a
[dcpomatic.git] / src / lib / server.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "server.h"
22 #include "dcpomatic_socket.h"
23 #include <boost/make_shared.hpp>
24
25 #include "i18n.h"
26
27 using boost::shared_ptr;
28 using boost::make_shared;
29
30 Server::Server (int port)
31         : _terminate (false)
32         , _acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port))
33 {
34
35 }
36
37 Server::~Server ()
38 {
39         boost::mutex::scoped_lock lm (_mutex);
40         _terminate = true;
41         _io_service.stop ();
42 }
43
44 void
45 Server::run ()
46 {
47         start_accept ();
48         _io_service.run ();
49 }
50
51 void
52 Server::start_accept ()
53 {
54         {
55                 boost::mutex::scoped_lock lm (_mutex);
56                 if (_terminate) {
57                         return;
58                 }
59         }
60
61         shared_ptr<Socket> socket = make_shared<Socket> ();
62         _acceptor.async_accept (socket->socket (), boost::bind (&Server::handle_accept, this, socket, boost::asio::placeholders::error));
63 }
64
65 void
66 Server::handle_accept (shared_ptr<Socket> socket, boost::system::error_code const & error)
67 {
68         if (error) {
69                 return;
70         }
71
72         handle (socket);
73         start_accept ();
74 }