5640843a03daa8e23c827e64868aa0536d406831
[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
24 #include "i18n.h"
25
26 using boost::shared_ptr;
27
28 Server::Server (int port)
29         : _terminate (false)
30         , _acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port))
31 {
32
33 }
34
35 Server::~Server ()
36 {
37         boost::mutex::scoped_lock lm (_mutex);
38         _terminate = true;
39         _acceptor.close ();
40         _io_service.stop ();
41 }
42
43 void
44 Server::run ()
45 {
46         start_accept ();
47         _io_service.run ();
48 }
49
50 void
51 Server::start_accept ()
52 {
53         {
54                 boost::mutex::scoped_lock lm (_mutex);
55                 if (_terminate) {
56                         return;
57                 }
58         }
59
60         shared_ptr<Socket> socket (new Socket);
61         _acceptor.async_accept (socket->socket (), boost::bind (&Server::handle_accept, this, socket, boost::asio::placeholders::error));
62 }
63
64 void
65 Server::handle_accept (shared_ptr<Socket> socket, boost::system::error_code const & error)
66 {
67         if (error) {
68                 return;
69         }
70
71         handle (socket);
72         start_accept ();
73 }