Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct packet {
- int type;
- int length;
- char *value;
- };
- class my_packet_reader
- {
- public:
- my_packet_reader(net::buffer &start)
- : m_buffer(start)
- {
- continue_with(&my_packet_reader::read_type);
- }
- bool read_handler(net::socket::tcp &socket, net::buffer &buffer)
- {
- m_buffer << buffer;
- return continue();
- }
- event<packet&>::collector_type& on_read()
- {
- return m_on_read.on_signal();
- }
- private:
- event<packet&> m_on_read;
- net::buffer m_buffer;
- packet m_packet;
- bool read_type()
- {
- if (buffer.size() >= 4) {
- buffer >> m_packet.type;
- continue_with(&my_packet_reader::read_length);
- }
- return false;
- }
- bool read_length()
- {
- if (buffer.size() >= 4) {
- buffer >> m_packet.length;
- continue_with(&my_packet_reader::read_value);
- }
- return false;
- }
- bool read_value()
- {
- if (buffer.size() >= m_packet.length) {
- m_packet.value = new char[m_packet.length];
- buffer.read(m_packet.value, m_packet.length);
- on_read(m_packet);
- return true;
- }
- return false;
- }
- };
- class my_protocol_socket : protected net::socket::tcp
- {
- public:
- my_protocol_socket()
- {
- on_read() += mem_fn(this, start_reading);
- m_packet_reader.on_read() += mem_fn(this, finish_reading);
- }
- event<packet&>::collector_type& on_packet()
- {
- return m_on_packet.on_signal();
- }
- private:
- event<packet&> m_on_packet;
- void start_reading(net::socket::tcp &socket, net::buffer buffer)
- {
- on_read() -= mem_fn(this, start_reading);
- on_read() += mem_fn(std::make_unique<my_packet_reader>(socket, buffer), my_packet_reader::read_handler);
- }
- void finish_reading(packet &data)
- {
- on_read() += mem_fn(this, start_reading);
- m_on_packet(data);
- }
- };
- void read_handler(packet &data)
- {
- // received reassebled packet!
- }
- int main()
- {
- my_protocol_socket sock;
- sock.on_packet() += read_handler;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement