title: When does a read() on a TCP socket return
body: <p>Can someone please explain, when exactly the read-function I use to get data from a TCP-socket does return? </p>
  
  <p>I use the code below for reading from a measurement system. This system delivers data with a frequency of 15 Hz. <code>READ_TIMEOUT_MS</code> has a value of <code>200</code>
  Furthermore <code>READ_BUFFER_SIZE</code> has a value of <code>40000</code>.
  All works fine, but what happens is, <code>read()</code> returns 15 times a second with <code>1349</code> bytes read.</p>
  
  <p>By reading Pitfall 5 in the following documentation I would have expected, that the buffer is filled up completely:</p>
  
  <p><a href="http://www.ibm.com/developerworks/library/l-sockpit/" rel="noreferrer">http://www.ibm.com/developerworks/library/l-sockpit/</a></p>
  
  <p>Init:</p>
  
  <pre><code>sock=socket(AF_INET, SOCK_STREAM, 0);
  if (socket &lt; 0)
  {
      goto fail0;
  }
  
  struct sockaddr_in server;
  server.sin_addr.s_addr = inet_addr(IPAddress);
  server.sin_family = AF_INET;
  server.sin_port = htons(Port);
  if (connect(sock,(struct sockaddr *)&amp;server, sizeof(server)))
  {
      goto fail1;
  }
  
  struct timeval tv;
  tv.tv_sec = READ_TIMEOUT_MS / 1000;
  tv.tv_usec = (READ_TIMEOUT_MS % 1000) * 1000;
  if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&amp;tv, sizeof(struct timeval)))
  {
      goto fail1;
  }
  
  return true;
  
  fail1:
      close(sock);
      sock = -1;
  fail0:
      return false;
  </code></pre>
  
  <p>Read:</p>
  
  <pre><code>unsigned char buf[READ_BUFFER_SIZE];
  int len = read(sock, buf, sizeof(buf));
  if (len &lt;= 0)
  {
      return NULL;
  }
  
  CBinaryDataStream* pData = new CBinaryDataStream(len);
  pData-&gt;WriteToStream(buf, len);
  return pData;
  </code></pre>
  
  <p>I hope this question is not a duplicate, because I searched for an answer before I asked.
  Please let me know if you need some further information.</p>