title: How Parse TCP Stream Consists of Custom-Protocol Packets Using Python
body: <p>Suppose we define a user-level TCP Packets parsing protocol as below:</p>
  
  <pre><code>  A User-Level TCP Packet:
    ---------- ------ ---------- ----------------------------
   | F1F2F3F4 | Type |  Length  |         Packet Body        |
    ---------- ------ ---------- ----------------------------
  
   1. F1F2F3F4: beginning of a packet, hex data (4 bytes)
   2. Type:     denotes what type of this packet (2 bytes)
   3. Length:   how many bytes the packet contains except F1F2F3F4
                Packets may have different length (2 bytes)
   4. PacketBody: Real data a packet contains
  </code></pre>
  
  <p>Say we have a TCP communication pair which exchange data with each other by sending packets in this format. The communicator sends <strong>lots of packets in a time</strong> through a socket, sometimes they even send files in this way. </p>
  
  <p>In C/C++ language I would alloc a buffer big enough to store data which reads from the socket, than scan the <strong>F1F2F3F4</strong> in the buffer and find the <strong>Length</strong> field, 
  if the data is less than <strong>Length</strong>, then wait for more. </p>
  
  <p>Now I need to implement this in Python, anybody knows how to do this? </p>