CppWAMP
C++11 client library for the WAMP protocol
asiolistener.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_ASIOLISTENER_HPP
8 #define CPPWAMP_INTERNAL_ASIOLISTENER_HPP
9 
10 #include <cstdint>
11 #include <set>
12 #include <utility>
13 #include "../error.hpp"
14 #include "../rawsockoptions.hpp"
15 #include "asioendpoint.hpp"
16 
17 namespace wamp
18 {
19 
20 namespace internal
21 {
22 
23 //------------------------------------------------------------------------------
24 template <typename TEstablisher>
25 class AsioListener : public AsioEndpoint<TEstablisher>
26 {
27 public:
28  using Establisher = TEstablisher;
29  using CodecIds = std::set<int>;
30 
31  AsioListener(Establisher&& est, CodecIds codecIds,
32  RawsockMaxLength maxRxLength)
33  : Base(std::move(est)),
34  codecIds_(std::move(codecIds)),
35  maxTxLength_(RawsockMaxLength::kB_64),
36  maxRxLength_(maxRxLength)
37  {}
38 
39 private:
40  using Base = AsioEndpoint<TEstablisher>;
41 
42 protected:
43  using Handshake = typename Base::Handshake;
44 
45  virtual void onEstablished() override {Base::receiveHandshake();}
46 
47  virtual void onHandshakeReceived(Handshake hs) override
48  {
49  auto peerCodec = hs.codecId();
50 
51  if (!hs.hasMagicOctet())
52  Base::fail(RawsockErrc::badHandshake);
53  else if (hs.reserved() != 0)
54  Base::sendHandshake(Handshake::eReservedBitsUsed());
55  else if (codecIds_.count(peerCodec))
56  {
57  maxTxLength_ = hs.maxLength();
58  Base::sendHandshake(Handshake().setMaxLength(maxRxLength_)
59  .setCodecId(peerCodec));
60  }
61  else
62  Base::sendHandshake(Handshake::eUnsupportedFormat());
63  }
64 
65  virtual void onHandshakeSent(Handshake hs) override
66  {
67  if (!hs.hasError())
68  Base::complete(hs.codecId(), Handshake::byteLengthOf(maxTxLength_),
69  Handshake::byteLengthOf(maxRxLength_));
70  else
71  Base::fail(hs.errorCode());
72  }
73 
74 private:
75  CodecIds codecIds_;
76  RawsockMaxLength maxTxLength_;
77  RawsockMaxLength maxRxLength_;
78 };
79 
80 } // namespace internal
81 
82 } // namespace wamp
83 
84 #endif // CPPWAMP_INTERNAL_ASIOLISTENER_HPP
wamp
Definition: anyhandler.hpp:36
wamp::RawsockErrc::badHandshake
@ badHandshake
Invalid handshake format from peer.
wamp::RawsockMaxLength
RawsockMaxLength
Enumerators used to specify the maximum length of messages that a raw socket transport can receive.
Definition: rawsockoptions.hpp:22
wamp::RawsockMaxLength::kB_64
@ kB_64
64 kilobytes