title: Sending/Receiving messages framed for serial communication over .Net Socket
body: <p>We have done some basic TCP communication, but have a few questions.  We are communicating with a TCP server where the transaction flow is described as follows:</p>
  
  <blockquote>
    <p>The sender initiates the transaction
    by sending an STX (ASCII 0x02)
    character, then waits for the
    recipient to reply by sending an ACK
    (ASCII 0x06) character.  After an ACK
    is received, the sender transmits a
    four-byte, unsigned, big-endian
    integer representing the size of the
    message payload, followed by the
    payload, and finally a 16-byte MD5
    message digest for the payload.  If
    the recipient is satisfied with the
    message, it sends an ACK character.</p>
  </blockquote>
  
  <pre><code>&lt;STX&gt; = ASCII 0x02
  &lt;ACK&gt; = ASCII 0x06
  
  Sender: &lt;STX&gt;     &lt;0x00&gt;&lt;0x00&gt;&lt;0x00&gt;&lt;0x05&gt;&lt;'H'&gt;&lt;'E'&gt;&lt;'L'&gt;&lt;'L'&gt;&lt;'O'&gt;&lt;0xEB&gt;&lt;0x61&gt;...
  Recipient:   &lt;ACK&gt;                                                                &lt;ACK&gt;
  </code></pre>
  
  <p>Using .Net sockets (System.Net.Sockets.Socket), what is the proper way to manage the STX/ACK transfer control?  Does the socket handle this automatically (i.e. Do we simply call socket.Send(byteData)), or do we need to explicitly send the STX, wait for ACK, etc.?</p>
  
  <p>The same goes for receiving: Do we simply receive the incoming data, or do we need to listen for an STX character, send an ACK, prepare for the payload, etc.?</p>
  
  <p>If the transfer control is handled automatically, are there any specific socket flags that we need to set?</p>
  
  <p>FYI: We found several links (like the following) that have proved useful for message framing, but none discuss the STX/ACK transfer control:</p>
  
  <ul>
  <li><a href="http://blogs.msdn.com/b/joncole/archive/2006/03/20/simple-message-framing-sample-for-tcp-socket.aspx" rel="nofollow">http://blogs.msdn.com/b/joncole/archive/2006/03/20/simple-message-framing-sample-for-tcp-socket.aspx</a></li>
  </ul>