Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A common pattern to deal with binary network protocols is define a struct that contains an union:</p> <pre><code>struct Message { Header hdr; union { Body1 msg1; Body2 msg2; Body3 msg3; }; }; </code></pre> <p>Semantically you are stating that a <code>Message</code> is composed of a <code>Header</code> and a body that can be one-of <code>Body1</code>, <code>Body2</code>... Now, provide insertion and extraction operators for the header and each body separately. Then implement the same operators for the <code>Message</code> by calling it on the <code>Header</code>, and depending on the message type, the body of the message that makes sense.</p> <p>Note that the elements of the union do not need to have the same size. The size of the union will be the maximum of it's members' sizes. This approach allows for a compact binary representation that can be read/written from the network. Your read/write buffer will be the <code>Message</code> and you will read just the header and then the appropriate body.</p> <pre><code>// Define operators: std::ostream&amp; operator&lt;&lt;( std::ostream&amp;, Header const &amp; ); std::ostream&amp; operator&lt;&lt;( std::ostream&amp;, Body1 const &amp; ); // and the rest // Message operator in terms of the others std::ostream&amp; opeartor&lt;&lt;( std::ostream&amp; o, Message const &amp; m ) { o &lt;&lt; m.header; switch ( m.header.type ) { case TYPE1: o &lt;&lt; m.body1; break; //... }; return o; } // read and dump the contents to stdout Message message; read( socket, &amp;message, sizeof message.header ); // swap the endianness, check size... read( socket &amp;message.msg1, message.header.size ); // ... std::cout &lt;&lt; message &lt;&lt; std::endl; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload