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