title: Reading from and writing to socket
body: <p>I've made a simple tcp server/client app where the client writes something to the server and it's then echoed back to the client. However, i'm having some problems when i'm trying to read what the server echoed back in the client.</p>
  
  <pre><code>string s;
  while((n = read(socketFD[0],readBuf, BUFFER_SIZE)) &gt; 0){
    cout&lt;&lt;"\nBytes read: "&lt;&lt;n&lt;&lt;endl;
    s.append(readBuf, n);
  }
  cout&lt;&lt;"\nTest after read\n";
  </code></pre>
  
  <p>I write 16 KB of text to the server. When i'm reading in the client I read 4 KB at a time.</p>
  
  <p>The output from this code is:</p>
  
  <pre><code>Bytes read: 4096
  
  Bytes read: 4096
  
  Bytes read: 4096
  
  Bytes read: 4046
  </code></pre>
  
  <p>The read call seem to block after it's done reading from the socket and never leave the loop. How can I fix this?</p>
  
  <p>EDIT: This is the code in the server that handles connected clients. </p>
  
  <pre><code>if((childpid = fork()) == 0){
    close(listenFD);
    while ((n = read(connectFD, buf, BUFFSIZE)) &gt; 0){
      cout&lt;&lt;"\nBytes read: "&lt;&lt;n&lt;&lt;endl;
      write(connectFD, buf, n);
    }
    cout&lt;&lt;"\nTest after read\n";
    exit(0);
  }
  </code></pre>
  
  <p>This output is:</p>
  
  <pre><code>Bytes read: 4096
  
  Bytes read: 4096
  
  Bytes read: 4096
  
  Bytes read: 4046
  
  Test after read
  </code></pre>
  
  <p>What's different here compared to the code in the client? Why doesn't the read call block as it does in the client? </p>