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