title: What is the correct way of reading from a TCP socket in C/C++?
body: <p>Here's my code:</p>
  
  <pre><code>// Not all headers are relevant to the code snippet.
  #include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;cstdlib&gt;
  #include &lt;cstring&gt;
  #include &lt;unistd.h&gt;
  
  char *buffer;
  stringstream readStream;
  bool readData = true;
  
  while (readData)
  {
      cout &lt;&lt; "Receiving chunk... ";
  
      // Read a bit at a time, eventually "end" string will be received.
      bzero(buffer, BUFFER_SIZE);
      int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);
      if (readResult &lt; 0)
      {
          THROW_VIMRID_EX("Could not read from socket.");
      }
  
      // Concatenate the received data to the existing data.
      readStream &lt;&lt; buffer;
  
      // Continue reading while end is not found.
      readData = readStream.str().find("end;") == string::npos;
  
      cout &lt;&lt; "Done (length: " &lt;&lt; readStream.str().length() &lt;&lt; ")" &lt;&lt; endl;
  }
  </code></pre>
  
  <p>It's a little bit of C and C++ as you can tell. The BUFFER_SIZE is 256 - should I just increase the size? If so, what to? Does it matter?</p>
  
  <p>I know that if "end" is not received for what ever reason, this will be an endless loop, which is bad - so if you could suggest a better way, please also do so.</p>