title: Sending pre-defined messages over TCP Sockets
body: <p>My question is about sending data from C# to C++ and the other way around.</p>
  
  <p>I have a "Server" and it is waiting for TCP connections from the "Clients". For the Server I am using C#/.NET and the Client is written in C++ with no extra libraries or dependencies (I want to keep it that way).</p>
  
  <p>On the Server side, a "Message" is being created an serialized into an array of bytes. A Message must start with the length of the data (excluding the length itself). Next must come an ID to identify its purpose (1 byte) and it may have some payload in the form of "int", "double", "string" etc.</p>
  
  <p>This is how a C#-Message gets serialized: <a href="https://pastebin.com/RM18HCk2" rel="nofollow noreferrer">https://pastebin.com/RM18HCk2</a></p>
  
  <p>An example Message can look like this:</p>
  
  <pre><code>    [0]     0x11    byte &lt; 4 bytes: Data length
      [1]     0x00    byte
      [2]     0x00    byte
      [3]     0x00    byte
      [4]     0x02    byte &lt; 1 byte: Message ID (here: 2)
      [5]     0x03    byte &lt; 4 bytes: Title length (here: "Abc")
      [6]     0x00    byte
      [7]     0x00    byte
      [8]     0x00    byte
      [9]     0x03    byte &lt; 1 byte: EO
      [10]    0x41    byte &lt; 3 bytes: Title (here: "Abc")
      [11]    0x62    byte
      [12]    0x63    byte
      [13]    0x03    byte &lt; 4 bytes: Message length (here: "Def")
      [14]    0x00    byte
      [15]    0x00    byte
      [16]    0x00    byte
      [17]    0x03    byte &lt; EOT
      [18]    0x44    byte &lt; 3 bytes: Message ("Def")
      [19]    0x65    byte
      [20]    0x66    byte
  </code></pre>
  
  <p>Now I want to recv this data on the C++ side and parse it. I put all the bytes I receive into a Buffer "std::deque MessageBuffer". This goes on until I have enough to read the Message-Length (4 bytes for int32). When I have the expected length, I wait until I have recv'd enough for the full Message.</p>
  
  <p>Now I somehow need to parse the "MessageBuffer". I want to call different functions based on the very first byte (which is the ID). Depending on the Message, I know the structure of the data. In C#, parsing it would be very simple by using a BinaryReader that handles all the problems for me.</p>
  
  <p><strong>Question: How do I parse the MessageBuffer in C++, without boost or other third party libraries?</strong></p>
  
  <p>I want to extract (in this case) the Title and the Text and put them into std::string on the C++ side. But of course, the same concept should work for all kinds of data.</p>
  
  <p>I have searched the Internet for the past two days. For some reasons, all examples I could find were sending and receiving std::string which is not at all what I want to do. Would std::istream be worth looking into?</p>
  
  <p>Note, that I am not looking for THE SOLUTION, rather I would love some advice on how things like that are done in C++-Land.</p>