title: How can I stop C++ recv() when string read is finished?
body: <p>I am reading an Image URL sent from a Java client to a C++ server from Sockets. The server stops reading through recv() when it detects there is a null character in the char buffer[] as I do below in the following code:</p>
  
  <pre><code>void * SocketServer::clientController(void *obj)
  {
      // Retrieve client connection information
      dataSocket *data = (dataSocket*) obj;
  
      // Receive data from a client step by step and append data in String message
      string message;
      int bytes = 0;
      do
      {
          char buffer[12] = {0};
          bytes = recv(data-&gt;descriptor, buffer, 12, 0);
  
          if (bytes &gt; 0) // Build message
          {
              message.append(buffer, bytes);
              cout &lt;&lt; "Message: " &lt;&lt; message &lt;&lt; endl;
          }
          else // Error when receiving it
              cout &lt;&lt; "Error receiving image URL" &lt;&lt; endl;
  
  
          // Check if we are finished reading the image link
          unsigned int i = 0;
          bool finished = false;
          while (i &lt; sizeof(buffer) / sizeof(buffer[0]) &amp;&amp; !finished)
          {
              finished = buffer[i] == '\0';
              i++;
          }
  
          if (finished)
              break;
  
      }
      while (bytes &gt; 0);
  
      cout &lt;&lt; message &lt;&lt; endl;
  
      close(data-&gt;descriptor);
      pthread_exit(NULL);
  }
  </code></pre>
  
  <p><strong><em>Is there a better and more elegant way to make this?</em></strong></p>
  
  <p>I read about sending first the size of the URL, but I do not know exactly how to stop recv() with it. I guess it is done by counting the bytes received until the size of the URL is reached. At that moment, we should be finished reading.</p>
  
  <p>Another approach could be closing the Java socket so that recv() will return -1 and the loop will be finished. However, considering my Java client waits for a response from C++ server, closing the socket and then reopen it does not seem a suitable option.</p>
  
  <p>Thank you,
  Héctor</p>