CppWAMP
C++11 client library for the WAMP protocol
udsopener.hpp
1 /*------------------------------------------------------------------------------
2  Copyright Butterfly Energy Systems 2014-2015, 2022.
3  Distributed under the Boost Software License, Version 1.0.
4  http://www.boost.org/LICENSE_1_0.txt
5 ------------------------------------------------------------------------------*/
6 
7 #ifndef CPPWAMP_INTERNAL_UDSOPENER_HPP
8 #define CPPWAMP_INTERNAL_UDSOPENER_HPP
9 
10 #include <cassert>
11 #include <memory>
12 #include <string>
13 #include <boost/asio/local/stream_protocol.hpp>
14 #include <boost/asio/strand.hpp>
15 #include "../asiodefs.hpp"
16 #include "../udspath.hpp"
17 
18 namespace wamp
19 {
20 
21 namespace internal
22 {
23 
24 //------------------------------------------------------------------------------
25 class UdsOpener
26 {
27 public:
28  using Info = UdsPath;
29  using Socket = boost::asio::local::stream_protocol::socket;
30  using SocketPtr = std::unique_ptr<Socket>;
31 
32  template <typename TExecutorOrStrand>
33  UdsOpener(TExecutorOrStrand&& exec, Info info)
34  : strand_(std::forward<TExecutorOrStrand>(exec)),
35  info_(std::move(info))
36  {}
37 
38  IoStrand strand() {return strand_;}
39 
40  template <typename F>
41  void establish(F&& callback)
42  {
43  struct Connected
44  {
45  UdsOpener* self;
46  typename std::decay<F>::type callback;
47 
48  void operator()(AsioErrorCode ec)
49  {
50  if (ec)
51  self->socket_.reset();
52  callback(ec, std::move(self->socket_));
53  self->socket_.reset();
54  }
55  };
56 
57  assert(!socket_ && "Connect already in progress");
58 
59  socket_.reset(new Socket(strand_));
60  socket_->open();
61  info_.options().applyTo(*socket_);
62 
63  // AsioConnector will keep this object alive until completion.
64  socket_->async_connect(info_.pathName(),
65  Connected{this, std::forward<F>(callback)});
66  }
67 
68  void cancel()
69  {
70  if (socket_)
71  socket_->close();
72  }
73 
74 private:
75  IoStrand strand_;
76  Info info_;
77  SocketPtr socket_;
78 };
79 
80 } // namespace internal
81 
82 } // namespace wamp
83 
84 #endif // CPPWAMP_INTERNAL_UDSOPENER_HPP
wamp::IoStrand
boost::asio::strand< AnyIoExecutor > IoStrand
Serializes I/O operations.
Definition: asiodefs.hpp:41
wamp
Definition: anyhandler.hpp:36
wamp::AsioErrorCode
boost::system::error_code AsioErrorCode
Type used by Boost.Asio for reporting errors.
Definition: asiodefs.hpp:44