]> git.tdb.fi Git - libs/net.git/blob - source/net/communicator.h
Decorate things which constitute the public API
[libs/net.git] / source / net / communicator.h
1 #ifndef MSP_NET_COMMUNICATOR_H_
2 #define MSP_NET_COMMUNICATOR_H_
3
4 #include <msp/core/except.h>
5 #include <msp/core/noncopyable.h>
6 #include <sigc++/signal.h>
7 #include "mspnet_api.h"
8 #include "protocol.h"
9
10 namespace Msp {
11 namespace Net {
12
13 class StreamSocket;
14
15 class MSPNET_API sequence_error: public invalid_state
16 {
17 public:
18         sequence_error(const std::string &w): invalid_state(w) { }
19 };
20
21 class MSPNET_API incompatible_protocol: public std::runtime_error
22 {
23 public:
24         incompatible_protocol(const std::string &w): std::runtime_error(w) { }
25 };
26
27
28 class MSPNET_API Communicator: public NonCopyable
29 {
30 public:
31         sigc::signal<void> signal_handshake_done;
32         sigc::signal<void, const std::exception &> signal_error;
33
34 private:
35         StreamSocket &socket;
36         const Protocol &protocol;
37         ReceiverBase &receiver;
38         int handshake_status = 0;
39         std::size_t buf_size = 65536;
40         char *in_buf = nullptr;
41         char *in_begin = nullptr;
42         char *in_end = nullptr;
43         char *out_buf = nullptr;
44         bool good = true;
45
46 public:
47         Communicator(StreamSocket &, const Protocol &, ReceiverBase &);
48         ~Communicator();
49
50         void initiate_handshake();
51         bool is_handshake_done() const { return handshake_status==2; }
52
53         template<typename P>
54         void send(const P &);
55
56 private:
57         void send_data(std::size_t);
58
59         void data_available();
60         bool receive_packet(const Protocol &, ReceiverBase &);
61         void send_handshake();
62 };
63
64 template<typename P>
65 void Communicator::send(const P &pkt)
66 {
67         send_data(protocol.serialize(pkt, out_buf, buf_size));
68 }
69
70 } // namespace Net
71 } // namespace Msp
72
73 #endif