2 #include "communicator.h"
6 using namespace Msp::Net;
14 class HandshakeProtocol: public Protocol
20 HandshakeProtocol::HandshakeProtocol():
23 add<Handshake>()(&Handshake::hash);
27 class HandshakeReceiver: public PacketReceiver<Handshake>
34 unsigned get_hash() const { return hash; }
35 virtual void receive(const Handshake &);
38 HandshakeReceiver::HandshakeReceiver():
42 void HandshakeReceiver::receive(const Handshake &shake)
53 Communicator::Communicator(StreamSocket &s, const Protocol &p, ReceiverBase &r):
59 in_buf(new char[buf_size]),
62 out_buf(new char[buf_size]),
65 socket.signal_data_available.connect(sigc::mem_fun(this, &Communicator::data_available));
68 Communicator::~Communicator()
74 void Communicator::initiate_handshake()
76 if(handshake_status!=0)
77 throw sequence_error("handshaking already done");
83 void Communicator::data_available()
88 in_end += socket.read(in_end, in_buf+buf_size-in_end);
94 if(handshake_status==2)
96 more = receive_packet(protocol, receiver);
100 HandshakeProtocol hsproto;
101 HandshakeReceiver hsrecv;
102 if((more = receive_packet(hsproto, hsrecv)))
104 if(hsrecv.get_hash()==protocol.get_hash())
106 if(handshake_status==0)
108 handshake_status = 2;
109 signal_handshake_done.emit();
124 bool Communicator::receive_packet(const Protocol &proto, ReceiverBase &recv)
126 int psz = proto.get_packet_size(in_begin, in_end-in_begin);
127 if(psz && psz<=in_end-in_begin)
129 char *pkt = in_begin;
131 proto.disassemble(recv, pkt, psz);
136 if(in_end==in_buf+buf_size)
138 unsigned used = in_end-in_begin;
139 memmove(in_buf, in_begin, used);
141 in_end = in_begin+used;
147 void Communicator::send_handshake()
150 shake.hash = protocol.get_hash();
152 HandshakeProtocol hsproto;
153 unsigned size = hsproto.assemble(shake, out_buf, buf_size);
154 socket.write(out_buf, size);