title: Sending and receiving all data (C++ sockets)
body: <p>Help me please to find out what is wrong in client-server communication...</p>
  
  <p>The client sends to server jpeg frames from camera 25 times per second using this function:</p>
  
  <pre><code>int SendAll(SOCKET &amp;client_socket, string &amp;data){
      int result, bytes_sent, sent_total, bytes_remain, package_size;
      result = bytes_sent = sent_total = package_size = 0;
      bytes_remain = data.size();
      while (bytes_remain &amp;&amp; !result){
          package_size = (bytes_remain&lt;KILOBYTE)?bytes_remain:KILOBYTE;
          bytes_sent = send(client_socket, &amp;data[sent_total], package_size, 0);
          if (bytes_sent &gt; 0){
              bytes_remain-= bytes_sent;
              sent_total+= bytes_sent;
          }
          else if(bytes_sent == SOCKET_ERROR){
              result = WSAGetLastError();
              break;
          }
      }
      return result;
  }
  </code></pre>
  
  <p>In thread loop:</p>
  
  <pre><code>while(CAMERA.Stream){
      OperationStartTime = GetTickCount();
      //RecvBuffer.resize(512);
      result = SendAll(CAMERA.Socket, CameraFrame);
      if(result != 0){
          cout &lt;&lt; "error in send - " &lt;&lt; result;
          CAMERA.Stream = false;
          break;
      }
      if (recv(CAMERA.Socket, &amp;RecvBuffer, 1, 0) &lt; 0){
          CAMERA.Stream = false;
          break;
      }  
      while(OperationStartTime + StreamRate &gt; GetTickCount()){
          if (!CAMERA.Stream){break;}
          Sleep(1);
      }
  }
  </code></pre>
  
  <p>Sometimes I see "error in send - 10053" (testing on localhost)</p>
  
  <p>Server uses this function to receive all data:</p>
  
  <pre><code>int RecvAll(SOCKET &amp;client_socket, string &amp;data){
      data = "";
      int bytes_received = 0;
      int result = 0;
      char* recv_buffer;
      do {
          recv_buffer = (char*)malloc(KILOBYTE);
          bytes_received = recv(client_socket, recv_buffer, KILOBYTE, 0);
          if (bytes_received &gt; 0){
              data.append(recv_buffer, bytes_received);
              if (bytes_received &lt; KILOBYTE || data.size() &gt;= 512*KILOBYTE){
                  bytes_received = result = 0;}
          }
          else if(bytes_received == SOCKET_ERROR){
              data.clear();
              result = WSAGetLastError();
          }
          free(recv_buffer);
      }
      while (bytes_received &gt; 0);
      return result;
  }
  </code></pre>
  
  <p>And no errors on server side.</p>
  
  <p>What is wrong in <code>SendAll</code>  and <code>RecvAll</code> functions and how to acheivea stabile data transfering?</p>
  
  <p><em>PS: and sometimes client stops, and only reconnecting helps. But if to reconnect, the server shows one more socket connected - it means that CAMERA.Socket was block and I don't understand why</em></p>