Advertisement
bueddl

Untitled

Oct 2nd, 2015
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. struct packet {
  2.     int type;
  3.     int length;
  4.     char *value;
  5. };
  6.  
  7. class my_packet_reader
  8. {
  9. public:
  10.     my_packet_reader(net::buffer &start)
  11.         : m_buffer(start)
  12.     {
  13.         continue_with(&my_packet_reader::read_type);
  14.     }
  15.  
  16.     bool read_handler(net::socket::tcp &socket, net::buffer &buffer)
  17.     {
  18.         m_buffer << buffer;
  19.         return continue();
  20.     }
  21.  
  22.     event<packet&>::collector_type& on_read()
  23.     {
  24.         return m_on_read.on_signal();
  25.     }
  26.  
  27. private:
  28.     event<packet&> m_on_read;
  29.     net::buffer m_buffer;
  30.     packet m_packet;
  31.  
  32.     bool read_type()
  33.     {
  34.         if (buffer.size() >= 4) {
  35.             buffer >> m_packet.type;
  36.             continue_with(&my_packet_reader::read_length);
  37.         }
  38.         return false;
  39.     }
  40.  
  41.     bool read_length()
  42.     {
  43.         if (buffer.size() >= 4) {
  44.             buffer >> m_packet.length;
  45.             continue_with(&my_packet_reader::read_value);
  46.         }
  47.         return false;
  48.     }
  49.  
  50.     bool read_value()
  51.     {
  52.         if (buffer.size() >= m_packet.length) {
  53.             m_packet.value = new char[m_packet.length];
  54.             buffer.read(m_packet.value, m_packet.length);
  55.             on_read(m_packet);
  56.             return true;
  57.         }
  58.         return false;
  59.     }
  60. };
  61.  
  62. class my_protocol_socket : protected net::socket::tcp
  63. {
  64. public:
  65.     my_protocol_socket()
  66.     {
  67.         on_read() += mem_fn(this, start_reading);
  68.         m_packet_reader.on_read() += mem_fn(this, finish_reading);
  69.     }
  70.  
  71.     event<packet&>::collector_type& on_packet()
  72.     {
  73.         return m_on_packet.on_signal();
  74.     }
  75.  
  76. private:
  77.     event<packet&> m_on_packet;
  78.  
  79.     void start_reading(net::socket::tcp &socket, net::buffer buffer)
  80.     {
  81.         on_read() -= mem_fn(this, start_reading);
  82.         on_read() += mem_fn(std::make_unique<my_packet_reader>(socket, buffer), my_packet_reader::read_handler);
  83.     }
  84.  
  85.     void finish_reading(packet &data)
  86.     {
  87.         on_read() += mem_fn(this, start_reading);
  88.         m_on_packet(data);
  89.     }
  90. };
  91.  
  92. void read_handler(packet &data)
  93. {
  94.     // received reassebled packet!
  95. }
  96.  
  97. int main()
  98. {
  99.     my_protocol_socket sock;
  100.  
  101.     sock.on_packet() += read_handler;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement