2 #include "communicator.h"
3 #include "streamsocket.h"
9 using namespace Msp::Net;
17 class HandshakeProtocol: public Protocol
23 HandshakeProtocol::HandshakeProtocol():
26 add<Handshake>()(&Handshake::hash);
30 class HandshakeReceiver: public PacketReceiver<Handshake>
37 unsigned get_hash() const { return hash; }
38 virtual void receive(const Handshake &);
41 HandshakeReceiver::HandshakeReceiver():
45 void HandshakeReceiver::receive(const Handshake &shake)
56 Communicator::Communicator(StreamSocket &s, const Protocol &p, ReceiverBase &r):
62 in_buf(new char[buf_size]),
65 out_buf(new char[buf_size]),
68 socket.signal_data_available.connect(sigc::mem_fun(this, &Communicator::data_available));
71 Communicator::~Communicator()
77 void Communicator::initiate_handshake()
79 if(handshake_status!=0)
80 throw sequence_error("handshaking already done");
86 void Communicator::send_data(unsigned size)
89 throw sequence_error("connection aborted");
90 if(handshake_status!=2)
91 throw sequence_error("handshake incomplete");
95 socket.write(out_buf, size);
97 catch(const std::exception &e)
100 if(signal_error.empty())
102 signal_error.emit(e);
106 void Communicator::data_available()
113 in_end += socket.read(in_end, in_buf+buf_size-in_end);
118 if(handshake_status==2)
120 more = receive_packet(protocol, receiver);
124 HandshakeProtocol hsproto;
125 HandshakeReceiver hsrecv;
126 if((more = receive_packet(hsproto, hsrecv)))
128 if(hsrecv.get_hash()==protocol.get_hash())
130 if(handshake_status==0)
132 handshake_status = 2;
133 signal_handshake_done.emit();
141 catch(const exception &e)
144 if(signal_error.empty())
146 signal_error.emit(e);
150 bool Communicator::receive_packet(const Protocol &proto, ReceiverBase &recv)
152 int psz = proto.get_packet_size(in_begin, in_end-in_begin);
153 if(psz && psz<=in_end-in_begin)
155 char *pkt = in_begin;
157 proto.dispatch(recv, pkt, psz);
162 if(in_end==in_buf+buf_size)
164 unsigned used = in_end-in_begin;
165 memmove(in_buf, in_begin, used);
167 in_end = in_begin+used;
173 void Communicator::send_handshake()
176 shake.hash = protocol.get_hash();
178 HandshakeProtocol hsproto;
179 unsigned size = hsproto.serialize(shake, out_buf, buf_size);
180 socket.write(out_buf, size);