2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG 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 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG 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.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../StdAfx.h"
24 #include "AsyncEventServer.h"
33 #include <boost/asio.hpp>
34 #include <boost/lexical_cast.hpp>
36 #include <tbb/mutex.h>
37 #include <tbb/concurrent_hash_map.h>
38 #include <tbb/concurrent_queue.h>
40 using boost::asio::ip::tcp;
42 namespace caspar { namespace IO {
46 typedef std::set<spl::shared_ptr<connection>> connection_set;
48 class connection : public spl::enable_shared_from_this<connection>
50 typedef tbb::concurrent_hash_map<std::wstring, std::shared_ptr<void>> lifecycle_map_type;
51 typedef tbb::concurrent_queue<std::string> send_queue;
53 const spl::shared_ptr<tcp::socket> socket_;
54 boost::asio::io_service& service_;
55 const spl::shared_ptr<connection_set> connection_set_;
56 const std::wstring name_;
57 protocol_strategy_factory<char>::ptr protocol_factory_;
58 std::shared_ptr<protocol_strategy<char>> protocol_;
60 std::array<char, 32768> data_;
61 lifecycle_map_type lifecycle_bound_objects_;
62 send_queue send_queue_;
65 class connection_holder : public client_connection<char>
67 std::weak_ptr<connection> connection_;
69 explicit connection_holder(std::weak_ptr<connection> conn) : connection_(std::move(conn))
72 void send(std::basic_string<char>&& data) override
74 auto conn = connection_.lock();
77 conn->send(std::move(data));
80 void disconnect() override
82 auto conn = connection_.lock();
88 std::wstring print() const override
90 auto conn = connection_.lock();
95 return L"[destroyed-connection]";
98 std::wstring address() const override
100 auto conn = connection_.lock();
103 return conn->address();
105 return L"[destroyed-connection]";
108 void add_lifecycle_bound_object(const std::wstring& key, const std::shared_ptr<void>& lifecycle_bound) override
110 auto conn = connection_.lock();
113 return conn->add_lifecycle_bound_object(key, lifecycle_bound);
116 std::shared_ptr<void> remove_lifecycle_bound_object(const std::wstring& key) override
118 auto conn = connection_.lock();
121 return conn->remove_lifecycle_bound_object(key);
123 return std::shared_ptr<void>();
128 static spl::shared_ptr<connection> create(spl::shared_ptr<tcp::socket> socket, const protocol_strategy_factory<char>::ptr& protocol, spl::shared_ptr<connection_set> connection_set)
130 spl::shared_ptr<connection> con(new connection(std::move(socket), std::move(protocol), std::move(connection_set)));
137 CASPAR_LOG(info) << print() << L" connection destroyed.";
140 std::wstring print() const
142 return L"[" + name_ + L"]";
145 std::wstring address() const
147 return u16(socket_->local_endpoint().address().to_string());
150 virtual void send(std::string&& data)
152 send_queue_.push(std::move(data));
153 service_.dispatch([=] { do_write(); });
156 virtual void disconnect()
158 service_.dispatch([=] { stop(); });
161 void add_lifecycle_bound_object(const std::wstring& key, const std::shared_ptr<void>& lifecycle_bound)
163 //thread-safe tbb_concurrent_hash_map
164 lifecycle_bound_objects_.insert(std::pair<std::wstring, std::shared_ptr<void>>(key, lifecycle_bound));
166 std::shared_ptr<void> remove_lifecycle_bound_object(const std::wstring& key)
168 //thread-safe tbb_concurrent_hash_map
169 lifecycle_map_type::const_accessor acc;
170 if(lifecycle_bound_objects_.find(acc, key))
172 auto result = acc->second;
173 lifecycle_bound_objects_.erase(acc);
176 return std::shared_ptr<void>();
181 void do_write() //always called from the asio-service-thread
186 if(send_queue_.try_pop(data))
188 write_some(std::move(data));
193 void stop() //always called from the asio-service-thread
195 connection_set_->erase(shared_from_this());
202 CASPAR_LOG_CURRENT_EXCEPTION();
205 CASPAR_LOG(info) << print() << L" Disconnected.";
208 const std::string ipv4_address() const
210 return socket_->is_open() ? socket_->remote_endpoint().address().to_string() : "no-address";
213 connection(const spl::shared_ptr<tcp::socket>& socket, const protocol_strategy_factory<char>::ptr& protocol_factory, const spl::shared_ptr<connection_set>& connection_set)
215 , service_(socket->get_io_service())
216 , name_((socket_->is_open() ? u16(socket_->local_endpoint().address().to_string() + ":" + boost::lexical_cast<std::string>(socket_->local_endpoint().port())) : L"no-address"))
217 , connection_set_(connection_set)
218 , protocol_factory_(protocol_factory)
221 CASPAR_LOG(info) << print() << L" Connected.";
224 protocol_strategy<char>& protocol() //always called from the asio-service-thread
227 protocol_ = protocol_factory_->create(spl::make_shared<connection_holder>(shared_from_this()));
232 void handle_read(const boost::system::error_code& error, size_t bytes_transferred) //always called from the asio-service-thread
238 std::string data(data_.begin(), data_.begin() + bytes_transferred);
240 CASPAR_LOG(trace) << print() << L" Received: " << u16(data);
242 protocol().parse(data);
246 CASPAR_LOG_CURRENT_EXCEPTION();
251 else if (error != boost::asio::error::operation_aborted)
255 void handle_write(const spl::shared_ptr<std::string>& str, const boost::system::error_code& error, size_t bytes_transferred) //always called from the asio-service-thread
259 CASPAR_LOG(trace) << print() << L" Sent: " << (str->size() < 512 ? u16(*str) : L"more than 512 bytes.");
260 if(bytes_transferred != str->size())
262 str->assign(str->substr(bytes_transferred));
263 socket_->async_write_some(boost::asio::buffer(str->data(), str->size()), std::bind(&connection::handle_write, shared_from_this(), str, std::placeholders::_1, std::placeholders::_2));
271 else if (error != boost::asio::error::operation_aborted)
275 void read_some() //always called from the asio-service-thread
277 socket_->async_read_some(boost::asio::buffer(data_.data(), data_.size()), std::bind(&connection::handle_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
280 void write_some(std::string&& data) //always called from the asio-service-thread
283 auto str = spl::make_shared<std::string>(std::move(data));
284 socket_->async_write_some(boost::asio::buffer(str->data(), str->size()), std::bind(&connection::handle_write, shared_from_this(), str, std::placeholders::_1, std::placeholders::_2));
287 friend struct AsyncEventServer::implementation;
290 struct AsyncEventServer::implementation
292 std::shared_ptr<boost::asio::io_service> service_;
293 tcp::acceptor acceptor_;
294 protocol_strategy_factory<char>::ptr protocol_factory_;
295 spl::shared_ptr<connection_set> connection_set_;
296 std::vector<lifecycle_factory_t> lifecycle_factories_;
299 implementation(std::shared_ptr<boost::asio::io_service> service, const protocol_strategy_factory<char>::ptr& protocol, unsigned short port)
300 : service_(std::move(service))
301 , acceptor_(*service_, tcp::endpoint(tcp::v4(), port))
302 , protocol_factory_(protocol)
315 CASPAR_LOG_CURRENT_EXCEPTION();
320 auto connections = *connection_set_;
321 for (auto& connection : connections)
328 spl::shared_ptr<tcp::socket> socket(new tcp::socket(*service_));
329 acceptor_.async_accept(*socket, std::bind(&implementation::handle_accept, this, socket, std::placeholders::_1));
332 void handle_accept(const spl::shared_ptr<tcp::socket>& socket, const boost::system::error_code& error)
334 if (!acceptor_.is_open())
339 auto conn = connection::create(socket, protocol_factory_, connection_set_);
340 connection_set_->insert(conn);
342 for (auto& lifecycle_factory : lifecycle_factories_)
344 auto lifecycle_bound = lifecycle_factory(conn->ipv4_address());
345 conn->add_lifecycle_bound_object(lifecycle_bound.first, lifecycle_bound.second);
351 void add_client_lifecycle_object_factory(const lifecycle_factory_t& factory)
353 service_->post([=]{ lifecycle_factories_.push_back(factory); });
357 AsyncEventServer::AsyncEventServer(
358 std::shared_ptr<boost::asio::io_service> service, const protocol_strategy_factory<char>::ptr& protocol, unsigned short port)
359 : impl_(new implementation(std::move(service), protocol, port)) {}
361 AsyncEventServer::~AsyncEventServer() {}
362 void AsyncEventServer::add_client_lifecycle_object_factory(const lifecycle_factory_t& factory) { impl_->add_client_lifecycle_object_factory(factory); }